当我进入应用程序的一个页面时,我会使用react路由器通过位置状态传递数据。然后我通过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,
});
};
}, []);
我认为这是react路由器想要的行为。如果你想重置状态,那么你需要做一些类似的事情
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;
工作示例
你试试相反的方法怎么样?将值存储在组件上并从该位置删除。我不确定这是否是最漂亮的解决方案,但我想这是最简单的
const [state,setState]=useState();
useEffect(()=>{
setState(location.state);
location.state=undefined;
}, [location])
试试这个方法:
import React, { useEffect } from "react";
import { useHistory } from "react-router-dom";
function Home() {
const history = useHistory();
function replaceHistory(e) {
if (e) {
e.preventDefault();
delete e.returnValue;
}
history.replace({ ...history.location, state: undefined });
}
console.log("history", history.location);
useEffect(() => {
window.addEventListener("beforeunload", () => replaceHistory);
return () => {
// Reset Location state if we leave this page
replaceHistory();
window.removeEventListener("beforeunload", replaceHistory);
};
}, []);
return (
<div>
<h2>Home</h2>
</div>
);
}
export default Home;
CodesandBox演示
react路由器的默认行为不会在刷新页面后保存历史状态,因此我们需要了解更多关于您的代码才能真正解决此问题。然而,如果状态确实保存了,您的第一次尝试似乎有一些缺陷,因为它使用了窗口的历史记录和位置,而不是道具。
function Page(props){
useEffect(() => {
const unloadFunc = () => {
//use the history and the location from the props instead of window
props.history.replace({
...props.location,
state: undefined,
});
}
window.addEventListener('onbeforeunload',unloadFunc);
return ()=>{
window.removeEventListener('onbeforeunload' unloadFunc);
//make history and location as the dependencies of the hook
}, [props.history, props.location]);
return <div></div>
}