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

标签 javascript reactjs react-router

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

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/

相关文章:

regex - 为什么react-router正确处理正则表达式 `path`,但同时抛出错误?

javascript - react native 。标签栏不改变场景跟随按钮

javascript - 在组件内 react :Unable to get this. state.name

javascript - json2html - 创建 HTML 表格

JavaScript 模板引擎

javascript - 如何使 FabricJS Canvas 上的所有对象都处于事件状态但作为一个组?

javascript - 在 Birt 处理程序上使用 Javascript reportContext.setPersistentGlobalVariable 方法

json - 使用 axios 渲染 json 数据

javascript - 用于点击跟踪的高阶 React 组件

reactjs - Formik 未捕获类型错误 : Cannot read property 'getFieldProps' of undefined