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

cat*_*use 13 javascript reactjs react-router

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

this.props.history.push({
  pathname: "/someotherpage",
  state: { somedata: somedata }
});   
Run Code Online (Sandbox Code Playgroud)

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

{this.props.location.state && (
    <SomeComponent>
        {this.props.location.state.somedata}
    </SomeComponent>
)}
Run Code Online (Sandbox Code Playgroud)

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

thi*_*ous 11

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

MDN 网络文档:History.replaceState()

History.replaceState() 方法修改当前历史记录条目,将其替换为方法参数中传递的 stateObj、标题和 URL

语法: history.replaceState(stateObj, title, [url]);

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

重点是它不会导致再次刷新。


Ash*_*ian 5

尝试这个:

history.replace('', null);
Run Code Online (Sandbox Code Playgroud)