【发布时间】:2018-06-06 01:44:08
【问题描述】:
对于如何将 React Router 的 history.push('/route') 与 Redux 一起使用,我有点不知所措。
也就是说,如果你用 Redux 的 mapDispatchToProps 连接一个组件,你怎么把应该在 dispatch 某个 action 后触发的 history.push('/route') 放在?
为了澄清这个问题,这是我的实验的 sn-p...
class PostContainer extends React.Component {
handleSubmit(data) {
return this.props.addPost(data);
}
render() {
return (<Post onSubmit={data=> this.handleSubmit(data)}/>);
}
}
const mapDispatchToProps = (dispatch) => {
return {
addPost: (data) => {
dispatch(addPost(data)).data.then((result) => {
dispatch(addPostFulfilled(result.data));
//How do you call the following function?
this.props.history.push('/posts')
}).catch((error) => {
dispatch(addPostRejected());
});
},
}
}
export default connect(null, mapDispatchToProps)(PostContainer);
如您所见,只要通过addPostFulfilled 将帖子添加到Redux 的状态,页面就需要通过history.push 移动到/posts。
根据 Redux 的文档,容器用于更新状态(以及获取数据)。所以,愚蠢的组件不应该放像history.push这样的东西。
有什么比上面的代码更好的方法?
我们将不胜感激。
【问题讨论】:
标签: javascript redux react-router react-redux