首页 > 解决方案 > 在从 Idp 重定向时,当来自状态的前一个 url 从来自 idp 的重定向重定向时,BrowserRouter 不会重新呈现

问题描述

我有一个使用 Auth0 设置的反应应用程序

当匿名用户直接导航到受保护的页面时

http://localhost:3000/appname/ProtectedPage 

我的组件底部的代码(Auth0 提供的库)

export default withAuthenticationRequired(ProtectedPage , {
  // Show a message while the user waits to be redirected to the login page.
  onRedirecting: () => (<div>Redirecting you to the login page...</div>),
});

将用户重定向到 Auth0 登录页面

成功登录后,用户将被重定向回授权的重定向 url (http://localhost:3000/appname)

auth0 库将状态传回,并将原始 url 加载到浏览器中。

此时的网址看起来像

http://localhost:3000/appname?code=asdasdadasdadasd

在此之后,从状态中提取原始 url,应用程序重定向到所需页面

http://localhost/appname/ProtectedPage 

到目前为止,这种行为是我想要的。

问题是我有一个 BrowserRouter 当原始响应返回时呈现

http://localhost:3000/appname?code=asdasdadasdadasd

这会渲染 HomeComponent

更多信息

我有两个组件

第一个组件包含 BrowserRouter

并且有这个效果

  useEffect(() => {
    console.log(`Called useEffect from FI ${window.location.pathname}`);
  }, [window.location.pathname]);

第二个组件(菜单组件)在 BrowserRouter 中渲染,但在 switch 之前并具有此 useEffect

  useEffect(() => {
    const path = window.location.pathname;
    console.log(`Called useEffect from FMH  ${path}`);
    setActiveItem(path);
  }, [window.location.pathname]);

我还使用了 DebugRouter 来尝试从浏览器路由器渲染更多细节

在从 idp 重定向时,我得到以下控制台输出

initial history is:  {
  "length": 26,
  "action": "POP",
  "location": {
    "pathname": "/appname",
    "search": "?code=12345&state=iamastate",
    "hash": ""
  }
}
VM188 main.chunk.js:500 Called useEffect from FMH  /appname
VM188 main.chunk.js:173 Called useEffect from FI /appname
VM188 main.chunk.js:500 Called useEffect from FMH  /appname/ProtectedPage

ProtectedPage 再次更改,但 BrowserRouter 未呈现正确的组件

我认为生命周期似乎是

Redirect received /appname?code 
BrowserRouter begings rendering 
Url is changed by auth component 
Menu component renders and sees the changed url
Browser Router finishes rendering with original url 

可能 useEffect 应该对来自 auth lib 的更改做出反应,但又不确定如何捕捉它

React-新手再次感谢

标签: javascriptreactjsreact-routerauth0

解决方案


推荐阅读