I'm a bit clueless as to how to use React Router's history.push('/route')
with Redux
.
In other words, if you connect a component with Redux's mapDispatchToProps
, how do you put history.push('/route')
that is supposed to be fired after dispatching a certain action?
To clarify the issue, here is a snippet of my experimentation...
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);
As you can see, as soon as a post is added into Redux's state through addPostFulfilled
, the page needs to move to /posts
via history.push.
According to Redux's doc, containers are made for updating states (as well as fetching data). So, dumb components are not supposed to put anything like history.push
.
What would be a better approach than the code above?
Any advice will be appreciated.
You can either user react-router-redux (require an initial set up) and dispatch your action from action creators
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);
or just pass push as a "done callback".
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);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments