本文介绍了下一个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
这篇关于下一个Js路由器beforePopState,处理程序中组件的访问状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!