下一个Js路由器beforePopState,处理程序中组件的访问状态
我正在使用下一个js Router.beforePopState事件,并且我想访问我在React组件(在其中定义此处理程序)中创建的useState变量的值,下面的示例代码,但是每当我访问该状态时,它为空或设置为默认值,例如,在下面的代码goaway状态值中,我总是以空字符串的形式进入处理程序""即使我在代码中设置了不同的值,是否有方法可以在处理程序中获取状态值?
const [goAway, setGoAway] = useState("");
const browserTabcloseHandler = e => {
e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
// Chrome requires returnValue to be set
e.returnValue = "";
};
useEffect(() => {
if (window) {
Router.beforePopState(() => {
//if (componentShouldBeSavedAsDraft(componentData)) {
const result = window.confirm("are you sure you want to leave?");
if (!result) {
window.history.pushState("/", "");
Router.push("/marketplace/upload-component");
}
console.log(goAway); // this value is always "" even though set differently in code.
return result;
});
window.onbeforeunload = browserTabcloseHandler;
}
//Router.events.on("routeChangeStart", handleRouteChange);
return () => {
if (window) {
window.onbeforeunload = null;
}
Router.beforePopState(() => {
return true;
});
};
}, []);
解决方案
我找到了相同的解决方案我缺少的是在使用中添加属性效果下面的代码修复了问题-
const [goAway, setGoAway] = useState("");
const browserTabcloseHandler = e => {
e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
// Chrome requires returnValue to be set
e.returnValue = "";
};
useEffect(() => {
if (window) {
Router.beforePopState(() => {
//if (componentShouldBeSavedAsDraft(componentData)) {
const result = window.confirm("are you sure you want to leave?");
if (!result) {
window.history.pushState("/", "");
Router.push("/marketplace/upload-component");
}
console.log(goAway); // this value is always "" even though set differently in code.
return result;
});
window.onbeforeunload = browserTabcloseHandler;
}
//Router.events.on("routeChangeStart", handleRouteChange);
return () => {
if (window) {
window.onbeforeunload = null;
}
Router.beforePopState(() => {
return true;
});
};
}, [goAway]); // this fixed the issue
相关文章