【发布时间】:2021-01-22 06:59:26
【问题描述】:
当我进入应用程序的一页时,我使用 react-router 通过位置状态传递数据。然后我通过location.state.myDataObject 访问它。当我刷新页面时它仍然存在,而我希望它是空的。这是我尝试使用的:
const resetLocation = () => {
history.replace({
...location,
state: undefined,
});
};
useEffect(() => {
window.addEventListener('onbeforeunload', resetLocation);
}, []);
或将其添加到useEffect 内的unmount 操作中,但我猜刷新页面时不会调用它:
useEffect(() => {
return function cleanLocationState() {
history.replace({
...this.props.location,
state: undefined,
});
};
}, []);
【问题讨论】:
-
您最终找到解决方案了吗?
-
不,我没有。
-
如果可以在codesandbox中显示示例代码,那就太好了。
-
您能否分享您拥有的任何其他反应路由器配置,因为默认行为似乎工作正常,它会在您刷新页面时重置状态,您可以在此代码和框中查看它codesandbox.io/s/state-react-router-5-1tlzb
Schedule链接设置状态 -
也许你的代码在你刷新的时候仍然会遍历整个流程?然后你不是刷新页面,而是从开始 index.js -> page1 运行应用程序(也许其他一些道具会自动导航到页面 2) -> page2。那么这可能是你的道具总是被设置的原因。我相信 react-router 应该不能自动保存任何数据。
标签: reactjs react-router react-hooks