【发布时间】:2018-05-17 20:00:57
【问题描述】:
更新:最新代码已上传到 GitHub - https://github.com/TechGnome/react-redux-refreshissue - 自下面发布的代码以来,已经发生了一些微妙但重要的变化 - 特别是 reducer 中的状态对象从数组更改为对象。
学习 React-Redux,这对这只老狗来说是一个新技巧。我已经阅读了几个教程,现在正试图将它提升到一个新的水平。当然,这并不容易,而且我在此过程中错过了一些东西。 首先是代码: 动作/MyNameActions.js
export const changeName = myNewName => ({
type: 'CHANGE_NAME',
myNewName
})
reducers/MyNameReducer.js
const MyName = (state = [], action) => {
console.log("REDUCER - action.myNewName: " + action.myNewName)
console.log("REDUCER - state.myNewName: " + state.myNewName)
switch (action.type) {
case 'CHANGE_NAME':
return [
...state,
{
myNewName: action.myNewName
}
]
default:
return state
}
}
export default MyName
组件/MyNameComponent.js
import React from 'react'
import { connect } from 'react-redux'
import { changeName } from '../actions/MyNameActions'
class MyName extends React.Component {
render() {
let input
console.log("0) component - render() - this.props")
console.log(this.props)
return(
<div>
<form
onSubmit={e => {
e.preventDefault()
if (!input.value.trim()) {
return
}
console.log("2) component - render() - this.props")
console.log(this.props)
this.props.changeName(input.value)
console.log("3) component - render() - this.props")
console.log(this.props)
input.value = ''
}}
>
<input ref={node => input = node} />
<button type="submit">
Change Name
</button>
</form>
Hi there, {this.state ? this.state.myNewName: this.props.myNewName}.
</div>
)
}
}
const mapDispatchToProps = (dispatch) => {
return {changeName: myNewName => dispatch(changeName(myNewName))}
}
const mapStateToProps = (state) => {
return {myNewName : state.myNewName}
}
export default connect(mapStateToProps, mapDispatchToProps)(MyName)
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import MyName from './reducers/MyNameReducer'
const store = createStore(MyName, {myNewName:"enter your name"})
ReactDOM.render(<Provider store={store}>
<App />
</Provider>, document.getElementById('root'));
最终结果应该是一个包含文本框、按钮和要求我输入姓名的文本的页面。输入文本并单击按钮后,文本应从“您好,请输入您的姓名”更改。 “嗨,techgnome。” (假设我在文本框中输入了 techgnome)。
只是没有。相反,它会变为“您好,”。
从组件代码中可以看出,我一路吐槽this.props,看的还行。它进入调度,reducer 运行的地方。而且,我在减速器中看到了正确的有效负载......但是当它从调度调用中返回时,它会恢复到以前的状态(而不是新状态)并且当它重新渲染组件时,不知何故这个。道具变得未定义! 什么什么?
现在已经盯着这个看了几个小时了&*搜索了interwebnettubes,但我什么也没找到。我很肯定我错过了一些简单而基本的东西,以至于我只见树木不见森林。
这也应该是一笔简单的交易。呵呵。
-tg
【问题讨论】:
标签: reactjs redux react-redux