我在我的应用程序中使用 React-redux,我在使用 connect(mapStateToProps,mapDispatchToProps)(Component)
时遇到了这个问题,并且能够使用映射成功地操作 redux 状态 dispatch 。使用开发工具,我看到状态已成功更改,但映射的 Prop 在任何组件中始终未定义。
我正在尝试的示例组件:
class DashboardPage extends React.Component {
componentWillMount() {
console.log(this.props.idToken);
}
render() {
return (
<div>
<div className="dashboard-container">
<p>{this.props.idToken}</p>
<button onClick={() => {this.props.logout()}}>
LOGOUT
</button>
<button onClick={() => {browserHistory.push('/app/play')}}>
PLAY
</button>
<button onClick={() => {this.props.setIsLoading(true)}}>
TEST
</button>
</div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
idToken: state.idToken,
};
};
export default connect(mapStateToProps, { logout, setIsLoading })(DashboardPage);
但是,这以前一直有效。我从代码中休息了一段时间,所以我不记得我做了什么来打破这个,但我很确定它与 React 路由器有关,所以这是我的路线:
export default (
<Route path="/" component={App}>
<Route path="app" component={Authorized}>
<IndexRedirect to="/app/dashboard"/>
<Route path="dashboard" component={DashboardPage} />
<Route path="play" component={PlayPage}/>
</Route>
<Route path="login" component={Login} />
</Route>
);
我基本上使用 App
作为主容器,我在其中调用一个 thunk Action 来检查 localStorage 中是否有 token ,如果是,则调用和 Action 重新应用 token 状态(相同成功登录时调用的操作)。此操作在重新应用状态之前将用户重定向到 /app/dashboard
,如果 localStorage 中没有保存凭据,应用程序将自动重定向到 /login
。
我的index.js
:
const appRoot = document.getElementById('app-root');
const store = createStore(reducers, compose(
applyMiddleware(thunk),
window.devToolsExtension ? window.devToolsExtension() : f => f
));
ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory} routes={routes} />
</Provider>
, appRoot);
我在路由方面做错了什么,导致 mapStateToProps
无法正确返回 props 吗?
在此先感谢您的帮助。
编辑:我刚刚将我的 mapStateToProps
编辑为此,以查看状态是否通过:
const mapStateToProps = (state) => {
console.log(state);
return {
idToken: state.idToken,
};
};
并且日志输出是undefined
最佳答案
我觉得你在更新状态时没有在 reducer 中添加你以前的状态。例如,如果您的新状态是 return {action.something},那么它可能是 {...state , action.something}。我有这样的问题。我不是专家,仍在工作和学习。
关于javascript - Redux 状态正在更改,但使用 mapStateToProps 时 Prop 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37376665/