【问题标题】:How to clear props.location.state on refresh?如何在刷新时清除 props.location.state?
【发布时间】:2019-04-16 04:00:36
【问题描述】:

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

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>
)}

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

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

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

    MDN Web Docs: History.replaceState()

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

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

    标题留空是安全的,网址是可选的。

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

    【讨论】:

    • 这种方法的问题在于它会清除所有历史记录并影响前进按钮。关于如何解决这个问题的任何其他想法?
    • 它正在工作,谢谢!这应该是正确答案?
    • history.replace('' null); 不适合我。它正在将我重定向到 / 但使用 history.replace(location.pathname, null); 工作正常!
    【解决方案2】:

    作为一种解决方法,您可以添加如下函数来区分 页面刷新this.props.history.push强>如下:

    isPageRefreshed() {
        return window.performance && performance.navigation.type === 1;
      }
    

    然后当你想检查它是否从其他页面刷新或重定向时,你可以这样使用

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

    参考:https://stackoverflow.com/a/50026758/8777471

    【讨论】:

      【解决方案3】:

      试试这个:

      history.replace('', null);
      

      【讨论】:

      • 足够接近了..我用history.replace('/currentroute', null);
      • 对我不起作用,我有这个错误Property 'replace' does not exist on type 'History'
      • 检查您的导入。我认为您正在导入错误的历史模块。它应该是 import { History } from 'history';
      • history.replace('' null); 不适合我。它正在将我重定向到 / 但使用 history.replace(location.pathname, null); 工作正常!
      猜你喜欢
      • 1970-01-01
      • 2019-06-21
      • 2018-11-17
      • 2017-06-03
      • 1970-01-01
      • 2013-01-14
      • 2019-02-11
      • 1970-01-01
      • 2012-05-19
      相关资源
      最近更新 更多