如何在页面重新加载时清除react-router中的location.state?

Pra*_*tha 9 javascript reactjs react-router

我目前正在通过以下方式改变路线:

<Link to={{
           pathname:`/transactions/${props.transaction.id}`,
           state: {transaction: props.transaction}
         }}> View Details </Link>
Run Code Online (Sandbox Code Playgroud)

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

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

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

Chr*_*ong 18

我也遇到了这个问题,我最终做的是从 react router 检索浏览器历史记录并清除特定的 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 });
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 14

不使用 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() 
}
Run Code Online (Sandbox Code Playgroud)


akr*_* bc 10

在 React Router V6 中,您可以使用 useNavigate() 清除当前路径的状态:

import React, { useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
useEffect(() => {
  const location = useLocation();
  const navigate = useNavigate();
  navigate(location.pathname, {}); 
  // reload and pass empty object to clear state
  // we can also use replace option: ..., {replace: true}
}, []);
Run Code Online (Sandbox Code Playgroud)


fro*_*975 9

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

window.history.replaceState({}, document.title)
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案。这确实需要任何第三方库,并且也不会重新加载浏览器。非常感谢@frodo2975 (2认同)

Cam*_*ong 5

使用状态后,再次调度具有空状态的操作以清理状态。

this.props.dispatch(replace({
  ...this.props.location,
  state: undefined
});
Run Code Online (Sandbox Code Playgroud)