我对如何使用 React Router 有点一无所知history.push('/route')
with Redux
.
换句话说,如果你将一个组件与 Redux 的连接mapDispatchToProps
,你怎么放history.push('/route')
应该在执行某个操作后被解雇?
为了澄清这个问题,这是我的实验的片段......
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);
正如你所看到的,一旦通过以下方式将帖子添加到 Redux 的状态中addPostFulfilled
,页面需要移动到/posts
通过历史记录.push。
根据 Redux 的文档,容器是为了更新状态(以及获取数据)而设计的。因此,愚蠢的组件不应该放置类似的东西history.push
.
比上面的代码更好的方法是什么?
任何建议将被认真考虑。
您可以使用react-router-redux(需要初始设置)并从操作创建者处分派您的操作
import { push } from 'react-router-redux'
class PostContainer extends React.Component {
handleSubmit(data) {
return this.props.addPost(data);
}
render() {
return (
<div>
<Post onSubmit={data=> this.handleSubmit(data)}/>
</div>
);
}
}
const mapDispatchToProps = (dispatch) => {
return {
addPost: (data) => {
dispatch(addPost(data)).data.then((result) => {
dispatch(addPostFulfilled(result.data));
//How do you call the following function?
dispatch(push('/posts'));
}).catch((error) => {
dispatch(addPostRejected());
});
},
}
}
export default connect(null, mapDispatchToProps)(PostContainer);
或者只是将推送作为“完成回调”传递。
class PostContainer extends React.Component {
handleSubmit(data, done) {
return this.props.addPost(data, done);
}
render() {
const { push } = this.props.history;
return (
<div>
<Post onSubmit={data=> this.handleSubmit(data, push)}/>
</div>
);
}
}
const mapDispatchToProps = (dispatch) => {
return {
addPost: (data, done) => {
dispatch(addPost(data)).data.then((result) => {
dispatch(addPostFulfilled(result.data));
//How do you call the following function?
done('/posts')
}).catch((error) => {
dispatch(addPostRejected());
});
},
}
}
export default connect(null, mapDispatchToProps)(PostContainer);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)