我目前正在通过路线更改来传递我的状态,如下所示:
<Link to={{
pathname:`/transactions/${props.transaction.id}`,
state: {transaction: props.transaction}
}}> View Details </Link>
我的逻辑是,如果“location.state.transaction”存在,则不获取新数据,否则获取数据。
现在的缺陷是页面重新加载时。如果用户重新加载页面,应用程序需要获取新数据。我认为如果重新加载,“location.state”会被清除,但显然状态保存在 sessionStorage 中。
我该如何解决这个问题? 我可以每次都获取新数据,但单击“查看详细信息”链接时不应获取数据。
如果您使用的是 React hooks,则可以直接使用
window.history
来清除状态而不触发重新渲染。这比使用 useHistory
钩子的 replace
方法要好,后者会导致组件重新渲染。
window.history.replaceState({}, '')
我也遇到了这个问题,我最终所做的是从 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 });
}
}
有更好的方法,无需使用 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()
}
在 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}
}, []);
使用状态后,再次调度一个空状态的操作来清理状态。
this.props.dispatch(replace({
...this.props.location,
state: undefined
});
history.replace({ state: {} })
。
如果您还想将用户重定向到某个地方,请使用 history.replace({ pathname: '/profile/me', state: {} })
在 React Router v6 中,您可以执行以下操作:
const location = useLocation();
const navigate = useNavigate();
const state = location.state;
// Do some stuff with the state
// ...
// Clear the state after
navigate(location.pathname, { replace: true });
导航到当前页面除了清除状态(修改历史记录)之外不会产生任何可见效果。
这可能有效。
const history = useHistory();
// consume the history.location.state and reset the state
useEffect(() => {
history.replace(`/transactions/${history.location.state.transaction.id}`, {});
}, []);
我建议不要在这里使用
location
属性,而是创建一个带有路径 /transactions/:transactionId
的路线(无论你在哪里定义它们),并在目标内部的 transactionId
属性中捕获 props.match.params.transactionId
成分。然后在 componentDidMount
中,您可以调度 API 请求操作以获取交易。不要忘记从链接的 props 中删除 state
参数。
这些都不会使用 useNavigate 重置我的状态。我要做的就是在导航上设置 useEffect。
...
const navigate = useNavigate()
...
useEffect(() => {
// set state here
....
},[navigate]