【问题标题】:How to redirect to an external url in React?如何在 React 中重定向到外部 url?
【发布时间】:2020-06-27 21:31:26
【问题描述】:

我正在尝试重定向到反应组件中的外部 URL。

我正在验证组件是否在本地存储中包含access_token 的加载时间。如果它不存在,我想重定向到身份验证提供程序以执行登录,然后在它重定向回我时存储令牌。

但是我发现将值分配给 window.location 或 window.location.href 或使用 window.location.replace(someUrl) 它不起作用,它只是将新 url 附加到我的应用程序 url。

这是我正在执行此操作的反应组件:

class App extends React.Component {
  componentDidMount() {
    if (!localStorage.getItem('access_token')) {
      window.location.replace(someUrl)
    } 
  }

  render() {
    return (
      <HashRouter>
        <React.Suspense fallback={loading()}>
          <Switch>
            <Route path="/" name="Home" render={props => <DefaultLayout {...props}/>}/>
          </Switch>
        </React.Suspense>
      </HashRouter>
    )
  }
}

在 React 中如何重定向到外部 URL 是否有不同的方法?

我也试过这个,但它不起作用,它将外部 URL 附加到我的应用程序之一: React-Router External link

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    使用 React Router Redirect 组件并在属性中提供地址。

    <Redirect push to="/somewhere/else" />
    

    https://reacttraining.com/react-router/web/api/Redirect

    【讨论】:

    • 这不起作用,也不能回答问题。他的意思是外部链接,例如如果您的域是 myapp.com - 他想被定向到“cnn.com”这种方法不起作用。它只会将您带到myapp.com/https://cnn.com,我们完全无效。
    猜你喜欢
    • 1970-01-01
    • 2016-09-09
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 2012-12-02
    相关资源
    最近更新 更多