首页 > 解决方案 > 反应路由器提示历史推送查询参数更改提示位置

问题描述

我在使用 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="作成中の書類を破棄します。よろしいですか?&quot;
            />
            ...
       </>
)

请任何人帮助我。谢谢!

标签: reactjsreact-routerreact-router-dom

解决方案


没有信息什么是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


推荐阅读