gpt4 book ai didi

javascript - 如何在刷新时清除 props.location.state?

转载 作者:行者123 更新时间:2023-11-29 20:48:22 29 4
gpt4 key购买 nike

我正在导航到另一个页面,其中正在传递一些数据,如下所示:

this.props.history.push({
pathname: "/someotherpage",
state: { somedata: somedata }
});

现在 /someotherpage ,我的 render() 有一个条件根据是否显示组件的方法 this.props.location.state不为空。

{this.props.location.state && (
<SomeComponent>
{this.props.location.state.somedata}
</SomeComponent>
)}

它正在工作。但是,当我刷新页面时,<SomeComponent>仍然显示,因为它仍然有 this.props.location.state.somedata即使我刷新也会存储。如何清除 this.props.location.state刷新页面时返回null? (虽然导航离开时似乎很清楚,但只有在刷新时它才会保留。)

最佳答案

使用window.history.replaceState(null, '')在值被消费后清除位置状态。

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]);

将标题留空是安全的,url 是可选的。

要点是它不会引起另一次刷新。

关于javascript - 如何在刷新时清除 props.location.state?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53278986/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com