【问题标题】:How do I clear location.state in react-router on page reload?如何在页面重新加载时清除 react-router 中的 location.state?
【发布时间】:2017-02-27 04:58:26
【问题描述】:

我目前正在通过如下路线更改状态:

<Link to={{
           pathname:`/transactions/${props.transaction.id}`,
           state: {transaction: props.transaction}
         }}> View Details </Link>

我的逻辑是,如果“location.state.transaction”存在,则不获取新数据,否则,获取数据。

现在的缺陷是页面重新加载时。如果用户重新加载页面,应用程序需要获取新数据。我认为如果重新加载,“location.state”会被清除,但显然状态保存在 sessionStorage 中。

我该如何解决这个问题? 我可以每次都获取新数据,但单击“查看详细信息”链接时不应获取数据。

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    使用完 state 后,再次 dispatch 一个空 state 的 action 来清理 state。

    this.props.dispatch(replace({
      ...this.props.location,
      state: undefined
    });
    

    【讨论】:

    • 被低估的答案
    【解决方案2】:

    我也遇到了这个问题,我最终做的是从反应路由器中检索浏览器历史记录并清除特定的 location.state 属性。所以在你的情况下,它将是transaction。我在componentDidMount 中执行此操作,以便在您第一次访问该页面后,该属性不再存在,

    import createHistory from 'history/createBrowserHistory'
    
    ...
    
    componentDidMount(){
        const history = createHistory();
        if (history.location.state && history.location.state.transaction) {
            let state = { ...history.location.state };
            delete state.transaction;
            history.replace({ ...history.location, state });
        }
    }
    

    【讨论】:

    • 不错的解决方案!
    • 一个@@router/LOCATION_CHANGE 被调度。但状态保持不变
    【解决方案3】:

    不使用 3 方库有更好的方法。

    我们可以使用history.replace()

    https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/history.md

    componentDidMount(){
     const {location,history} = this.props;
     //use the state via location.state
     //and replace the state via
     history.replace() 
    }
    

    【讨论】:

      【解决方案4】:

      我建议不要在这里使用location 道具,而是创建一个带有路径的路由(无论您定义它们):/transactions/:transactionId,并在道具props.match.params.transactionId 中捕获transactionId目标组件。然后在componentDidMount 中,您可以分派 API 请求操作以获取交易。不要忘记从 Link 的 props 中删除 state 参数。

      【讨论】:

        【解决方案5】:

        如果你使用 react 钩子,你可以直接使用window.history 来清除状态而不触发重新渲染。这比使用 useHistory 钩子的 replace 方法要好,后者会导致您的组件重新渲染。

        window.history.replaceState({}, document.title)
        

        【讨论】:

        • 这应该是公认的答案。这确实需要任何 3rd 方库,也不需要重新加载浏览器。非常感谢@frodo2975
        【解决方案6】:

        这可能会奏效。

        const history = useHistory();
        // consume the history.location.state and reset the state
        useEffect(() => {
            history.replace(`/transactions/${history.location.state.transaction.id}`, {});
          }, []);
        

        【讨论】:

          【解决方案7】:

          history.replace({ state: {} })。 如果您还想将用户重定向到某个地方,请使用history.replace({ pathname: '/profile/me', state: {} })

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-03-30
            • 2016-01-23
            • 2018-01-13
            • 2021-06-29
            • 1970-01-01
            • 2019-01-05
            • 2022-01-24
            • 2010-11-19
            相关资源
            最近更新 更多