reactjs - React hooks - 当我们刷新页面时从 react-router 位置状态中删除
问题描述
当我进入应用程序的一页时,我使用 react-router 通过位置状态传递数据。然后我通过location.state.myDataObject
. 当我刷新页面时它仍然存在,而我希望它是空的。这是我尝试使用的:
const resetLocation = () => {
history.replace({
...location,
state: undefined,
});
};
useEffect(() => {
window.addEventListener('onbeforeunload', resetLocation);
}, []);
或将其添加到unmount
操作中,useEffect
但我猜刷新页面时不会调用它:
useEffect(() => {
return function cleanLocationState() {
history.replace({
...this.props.location,
state: undefined,
});
};
}, []);
解决方案
我认为这是反应路由器的期望行为。如果你想重置状态,那么你需要做类似的事情
import React, { useEffect, useCallback } from "react";
import { useLocation, useHistory } from "react-router-dom";
function Home() {
const location = useLocation();
const history = useHistory();
const replaceHistory = useCallback(() => {
history.replace({ ...location, state: undefined });
}, [history]);
useEffect(() => {
window.addEventListener("beforeunload", () => replaceHistory);
return () => {
window.removeEventListener("beforeunload", replaceHistory);
};
}, []);
return (
<div>
<h2>Home</h2>
</div>
);
}
export default Home;
工作示例
推荐阅读
- java - 正则表达式如何匹配字符串中不重复的子字符串?
- elixir - 匿名函数意外输出
- bash - 检查状态代码和内容的 wget 响应
- in-app-billing - 如何从 Google Play Billing 获取购买状态?
- android - 无法解析配置“:app:_internal_aapt2_binary”的所有文件
- android - bottomsheetdialog 中页面底部的额外边距
- swift - 如何修复“动态”属性“IpfSetId”也必须是“@objc”?
- vba - Vba 中的 Power Bi 数据刷新
- fastreport - FastReport 文档属性(标题、主题、版本、作者)设置
- android - RecyclerView Adapter 的 onBindViewHolder 方法 setImageResource 有效