我认为这是非常原始的。我有两件事有问题:
1. this.props.appState
是构造函数中的undefined
。这是出乎意料的,因为在 reducer 中,我将初始状态设置为 { appState: { name: "World!" } }
并且我期望这会导致 appState
的初始化。所以我添加了 if 语句,我知道这只是在找到实际问题之前的临时修复。
2.当我点击按钮并调用sendAction
处理程序时,执行流程永远不会到达reducer函数!
class App extends React.Component {
constructor(props) {
super(props);
if (this.props.appState) {
this.state = { name: this.props.appState.name };
}
else {
this.state = { name: "Unknown" };
}
this.nameChanged = this.nameChanged.bind(this);
this.sendAction = this.sendAction.bind(this);
}
nameChanged(event) {
this.setState({ name: event.target.value });
}
sendAction(event) {
this.props.saveName(this.state.name);
}
render() {
return (
<pre>
<h1>Hello, {this.state.name}!</h1>
<input type="text" value={this.state.name} onChange={this.nameChanged} />
<input type="button" value="Click me!" onClick={this.sendAction} />
</pre>
);
}
}
const appReducer = (state = { appState: { name: "World!" } }, action) => {
debugger;
switch (action.type) {
case "SAVE_NAME":
return Object.assign({}, state, { name: action.name });
default:
return state;
}
};
const AppContainer = ReactRedux.connect(
state => ({ appState: state.appState }),
dispatch => ({
saveName: (name) => Redux.bindActionCreators({ type: "SAVE_NAME", name }, dispatch)
})
)(App);
const combinedReducers = Redux.combineReducers({
appReducer
});
const store = Redux.createStore(combinedReducers);
ReactDOM.render(
<ReactRedux.Provider store={store}>
<AppContainer />
</ReactRedux.Provider>,
document.getElementsByTagName('main')[0]
);
最佳答案
由于您的 reducer 被称为: appReducer
,您将需要像这样访问 appState
中的 appReducer.appState
上的 mapStateToProps
属性
const AppContainer = ReactRedux.connect(
state => ({ appState: state.appReducer.appState }),
dispatch => ({
saveName: (name) => Redux.bindActionCreators({ type: "SAVE_NAME", name }, dispatch)
})
)(App);
对于你的第二个问题,你可以做
const mapDispatchToProps = (dispatch, ownProps) => {
return {
saveName: (name) => {
dispatch({ type: "SAVE_NAME", name })
}
}
}
或者像这样定义它。
const actionCreators = {
saveName: (name) => {
return { type: "SAVE_NAME", name }
},
}
const mapDispatchToProps = (dispatch, ownProps) => {
return bindActionCreators(actionCreators, dispatch);
}
然后在连接
const AppContainer = ReactRedux.connect(
state => ({ appState: state.appReducer.appState }),
mapDispatchToProps,
})
)(App);
关于reactjs - react + Redux : undefined initial state and reducer not called as expected,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47679314/