gpt4 book ai didi

reactjs - react + Redux : undefined initial state and reducer not called as expected

转载 作者:行者123 更新时间:2023-12-03 13:45:46 25 4
gpt4 key购买 nike

我认为这很原始。我在两件事上遇到了麻烦:

1. this.props.appStateundefined在构造函数中。这是意想不到的,因为在 reducer 中我将初始状态设置为 { appState: { name: "World!" } }我期待这会导致 appState 的初始化。因此,我添加了 if 语句,我知道这只是在找到实际问题之前的临时修复。

2.当我点击按钮并调用 sendAction handler,执行流程永远不会到达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,因此您需要访问 mapStateToProps< 中的 appReducer.appState 上的 appState 属性 像这样

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com