Javascript 如何在页面重新加载时清除react router中的location.state?
我目前正在通过以下路线更改的状态:Javascript 如何在页面重新加载时清除react router中的location.state?,javascript,reactjs,react-router,Javascript,Reactjs,React Router,我目前正在通过以下路线更改的状态: <Link to={{ pathname:`/transactions/${props.transaction.id}`, state: {transaction: props.transaction} }}> View Details </Link> 查看详细信息 我的逻辑是,如果存在“location.state.transaction”,就不要获取新数据,否则就获取
<Link to={{
pathname:`/transactions/${props.transaction.id}`,
state: {transaction: props.transaction}
}}> View Details </Link>
查看详细信息
我的逻辑是,如果存在“location.state.transaction”,就不要获取新数据,否则就获取数据
现在,该漏洞出现在页面重新加载时。如果用户重新加载页面,应用程序需要获取新数据。我以为如果重新加载,“location.state”会被清除,但很明显,状态保存在sessionStorage中
我如何解决这个问题?
我可以每次只提取新数据,但在单击“查看详细信息”链接时不应提取数据。使用状态后,再次发送状态为空的操作以清除状态
this.props.dispatch(replace({
...this.props.location,
state: undefined
});
我也遇到了这个问题,我最终做的是从react router检索浏览器历史记录并清除特定的location.state属性。因此,在您的情况下,它将是
事务
。我在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 });
}
}
不使用三方库有更好的方法 我们可以使用
history.replace()
我建议不要在这里使用
位置
属性,而是创建一个路径为:/transactions/:transactionId
的路由(无论您在何处定义它们),并在目标组件内部的propprops.match.params.transactionId
中捕获transactionId
。然后在componentDidMount
中,您可以调度API请求操作以获取事务。不要忘记从链接的道具中删除状态
参数。如果您使用的是react钩子,则可以直接使用window.history
清除状态,而无需触发重新渲染器。这比使用useHistory
hook的replace
方法要好,这样会导致组件重新加载
window.history.replaceState({}, document.title)
这可能会奏效
const history = useHistory();
// consume the history.location.state and reset the state
useEffect(() => {
history.replace(`/transactions/${history.location.state.transaction.id}`, {});
}, []);
很好的解决方案!!已调度@@router/LOCATION\u更改。但国家仍然是同一个估计的答案这是唯一对我有效的答案。
const history = useHistory();
// consume the history.location.state and reset the state
useEffect(() => {
history.replace(`/transactions/${history.location.state.transaction.id}`, {});
}, []);