admin管理员组文章数量:1186444
I am navigating to another page where in am passing some data like so:
this.props.history.push({
pathname: "/someotherpage",
state: { somedata: somedata }
});
Now on /someotherpage
, I have a condition in my render()
method to show a component depending on whether this.props.location.state
is not null.
{this.props.location.state && (
<SomeComponent>
{this.props.location.state.somedata}
</SomeComponent>
)}
It's working. However, when I refresh the page, <SomeComponent>
still shows up as it still has the this.props.location.state.somedata
stored even if I refresh. How do I clear this.props.location.state
back to null when refreshing the page? (It seems to clear though when navigating away, only on refresh it gets retained.)
I am navigating to another page where in am passing some data like so:
this.props.history.push({
pathname: "/someotherpage",
state: { somedata: somedata }
});
Now on /someotherpage
, I have a condition in my render()
method to show a component depending on whether this.props.location.state
is not null.
{this.props.location.state && (
<SomeComponent>
{this.props.location.state.somedata}
</SomeComponent>
)}
It's working. However, when I refresh the page, <SomeComponent>
still shows up as it still has the this.props.location.state.somedata
stored even if I refresh. How do I clear this.props.location.state
back to null when refreshing the page? (It seems to clear though when navigating away, only on refresh it gets retained.)
4 Answers
Reset to default 12Use window.history.replaceState(null, '')
to clear the location state after the value is consumed.
MDN Web Docs: History.replaceState()
The History.replaceState() method modifies the current history entry, replacing it with the stateObj, title, and URL passed in the method parameters
Syntax: history.replaceState(stateObj, title, [url]);
It's safe to leave title blank and url is optional.
The main point is that It doesn't cause another refresh.
Try this:
history.replace('', null);
As a workaround you can add function like below to differentiate page refresh from this.props.history.push as below:
isPageRefreshed() {
return window.performance && performance.navigation.type === 1;
}
Then when you want to check if it is refreshed or redirected from other page, you can use like that
{!this.isPageRefreshed && this.props.location.state && (
<SomeComponent>
{this.props.location.state.somedata}
</SomeComponent>
)}
Reference: https://stackoverflow.com/a/50026758/8777471
You can do this by setting the current history entry's state to null
like this:
const { state, pathname } = useLocation();
history.replace(pathname, null);
本文标签: javascriptHow to clear propslocationstate on refreshStack Overflow
版权声明:本文标题:javascript - How to clear props.location.state on refresh? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738313647a2074175.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论