【问题标题】:Redirect to third party url using react-router-dom使用 react-router-dom 重定向到第三方 url
【发布时间】:2019-03-11 13:47:53
【问题描述】:

我非常了解我想要对组件进行条件渲染的 react-router-dom。如果用户未登录,则将他重定向到某个第三方 URL

例如,下面的代码看起来很整洁并且工作正常

<Route exact path="/home" render={() => (
  isLoggedIn() ? (
    <Redirect to="/front"/>
  ) : (
   <Home />
  )
)}/>

假设在上面的例子中,如果我想重定向to https://www.google.com我该怎么做?

如果我写

 <Redirect to="https://www.google.com"> it gives me error. 

如何重定向到第三方网站?

【问题讨论】:

标签: reactjs react-router-v4 react-router-dom


【解决方案1】:

您可以为外部网址使用标签,

<a href='https://domain.extension/external-without-params'>external</a>

但你也可以提供这样的组件:

<Route path='/external' component={() => { window.location = 'https://domain.extension/external-without-params'; return null;} }/>

【讨论】:

    【解决方案2】:

    您可以使用window.open() 重定向到任何网站。

    例如:

    window.open('https://www.google.com');
    

    在您的代码中实现重定向:

    render () {
      if(this.isLogin) {
        return(/* your components*/);
      } else {
        window.open('https://www.google.com');
        return (<div></div>); //render function should return something
      }
    }
    

    您也可以指定目标属性或窗口名称,详情请见w3school tutorial about this function

    【讨论】:

      【解决方案3】:

      如果您使用的是 Typescript,您可能会在接受的答案中收到以下错误:

      Type 'string' is not assignable to type 'Location'
      

      要解决这个问题,您只需要使用 window.location.href

      <Route path="/external" component={() => {window.location.href = config.UPGRADE_URL return null }} />
      

      【讨论】:

        【解决方案4】:

        请记住,您无法使用 &lt;Link /&gt;&lt;NavLink /&gt; 执行此操作,因为它们主要用于在单页应用程序中进行路由。

        您应该改用锚标记。 示例:&lt;a href="https://www.google.com"&gt;Google&lt;/a&gt;

        【讨论】:

          【解决方案5】:

          只需这样做就可以轻松使用按钮:

          <button onClick={(e) => (window.location = 'https://www.google.com')}>Click me</button>
          

          【讨论】:

          • 这条路线没有按钮进入图片,所以经过验证的答案是正确的做法。
          猜你喜欢
          • 1970-01-01
          • 2022-06-24
          • 1970-01-01
          • 2023-02-19
          • 2019-06-28
          • 2018-02-04
          • 2019-02-05
          • 2018-05-21
          • 2021-10-09
          相关资源
          最近更新 更多