【问题标题】:React Routes redirect to external URL for Auth linksReact Routes 重定向到 Auth 链接的外部 URL
【发布时间】:2019-03-18 11:50:22
【问题描述】:

我有一个代码示例,我试图重定向尚未登录的用户。我正在使用外部身份验证来发送用户通过第 3 方身份验证系统登录。我知道 react-routes 有 Redirect 选项,我知道它们只重定向到路径名。有没有办法让window.assign 发生重定向,从而将用户立即重定向到不同的页面?

提前谢谢你!

const ProtectedRoute = (auth, component: Component, ...rest) => {
  return <Route
    {...rest}
    render={props => auth.isAuthenticated()
      ? <Component {...props} />
      : <Redirect
        to={{
          pathname: 'http://example.com/',
          state: { from: props.location },
        }}
      />
    }
  />;
};

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    您可以评估组件的 componentDidMount 挂钩中的日志记录道具,并使用 window.location 重定向到完全不同的 URL。例如:

    componentDidMount() {
        if(auth.isAuthenticated()) {
          return <Component {...props} />
        }
        window.location.assign('http://example.com/');
    }
    

    【讨论】:

    • 组件是否应该是React.PureComponent?以便我调用尽可能多的代码?
    • 不必如此,您也可以在任何常规组件中对此进行评估。
    • 是的,当我将用户重定向到新页面时它工作正常,事件页面是空白的,它仍然呈现我实际需要的内容
    猜你喜欢
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    • 2012-03-23
    • 2014-08-09
    • 1970-01-01
    • 2017-12-11
    • 2012-01-10
    相关资源
    最近更新 更多