reactjs - 反应路由器提示历史推送查询参数更改提示位置
问题描述
我在使用 react-router Prompt 组件时遇到问题。
我想在用户重新加载或离开页面时警告用户,但在我将查询参数添加到 url 时除外 1 种情况。
我已经这样做了,但是当我在进行更改后刷新页面时。我回到路径“/”而不是我正在处理的当前页面。
示例:我正在处理路径“create-contract”。然后,如果用户单击按钮,我想添加查询 ?screen={screen} 。
现在我有“create-contract?screen={screen}”然后如果我刷新页面并确认或返回上一个 url “create-contract”并刷新。
我将转到路径“/”。我认为是错误的。
当我刷新时,我希望它仍然在当前页面中。
这里的代码:
useEffect(() => {
if (shouldBlockNavigation) {
const existingHandler = window.onbeforeunload;
window.onbeforeunload = (event) => {
if (existingHandler) existingHandler(event);
return true;
};
} else {
if (screen) {
history.push("?screen=" + screen);
} else {
history.push(RouteConstant.Contract.CreateContract.path);
}
}
return () => {
window.onbeforeunload = null;
};
}, [shouldBlockNavigation, screen]);
return (
<>
<Prompt
when={shouldBlockNavigation}
message="作成中の書類を破棄します。よろしいですか?"
/>
...
</>
)
请任何人帮助我。谢谢!
解决方案
没有信息什么是screen
可变的。
在我看来,重新加载后它会进入这一部分:
else {
if (screen) {
history.push(RouteConstant.Contract.CreateContract.path + "?screen=" + screen);
} else {
history.push(RouteConstant.Contract.CreateContract.path); // goes here
}
}
要解决这个问题,您可以尝试获取当前位置,解析它,如果它包含?screen=screen
从此 url 获取屏幕并使用它
要获取当前位置,您可以使用useLocation()
fromreact-router-dom
推荐阅读
- c++ - 如何通过 CMakeLists.txt 在 C++ 项目中使用 Caffe 库
- windows - 如何在 Docker Windows 容器中设置屏幕分辨率?
- html - 在 RMarkdown 中,如何在使用 HTML 或 Word 输出时包含乳胶代码
- javascript - 如何在变量中获取和存储 html 对象标记的数据值以通过 javascript 进行比较
- python - 树莓派wifi信号通过UDP或TCPIP传输不一致
- r - 使用 R 数据帧中的值来规范化另一个数据帧的列
- java - 可以根据 JRE/JVM 版本将我的类/方法标记为已弃用吗?
- java - 有没有办法将 LambdaExpression 转换为字符串
- mongodb - Mongoose 5.11.11 SchemaDefinition 键入
- python - 发生 Azure 函数故障,要创建哪个 App Insights 警报?