Reputation: 3
Every time I change the route, I send a message through location`s state. I want to remove that message when componentWillUnmont().
`this.context.router.push({
pathname: '/EmpReferralListView',
state: {
message: (typeof message != 'undefined') ? message : ''
}
});`
Upvotes: 0
Views: 3839
Reputation: 21
For anyone stuck on a similar problem like I was...This is for react router v4.
What you can do, instead, is hook into the componentWillMount()
method.
Define the message
in your component's constructor:
constructor(props) {
super(props);
this.message = '';
}
Then your componentWillMount()
will look like this:
componentWillMount() {
if (this.props.location.state && this.props.location.state.message) {
this.message = this.props.location.state.message;
this.props.history.replace({
pathname: this.props.location.pathname,
state: {}
});
}
}
The above code will replace the location's state after you've grabbed the message. So you'll want to use this.message
to display that message moving forward.
Now, you can reference your message during render like so:
render() {
return (
<div>{this.message}</div>
);
}
Your message should clear when the location changes.
I would recommend creating a component specifically for this task which you can then include in any component which you're expecting the message.
Upvotes: 2