【问题标题】:What is the best way to redirect a page using React Router? [closed]使用 React Router 重定向页面的最佳方法是什么? [关闭]
【发布时间】:2017-12-18 18:04:36
【问题描述】:

我是 React Router 的新手,我了解到重定向页面的方法有很多:

  1. 使用browserHistory.push("/path")

    import { browserHistory } from 'react-router';
    //do something...
    browserHistory.push("/path");
    
  2. 使用this.context.router.push("/path")

    class Foo extends React.Component {
        constructor(props, context) {
            super(props, context);
            //do something...
        }
        redirect() {
            this.context.router.push("/path")
        }
    }
    
    Foo.contextTypes = {
        router: React.PropTypes.object
    }
    
  3. 在 React Router v4 中,有 this.context.history.push("/path")this.props.history.push("/path")。详情:How to push to History in React Router v4?

我对所有这些选项感到很困惑,有没有最好的方法来重定向页面?

【问题讨论】:

  • 您使用的是 v4 是吗?
  • 您发布的另一个堆栈的链接非常清晰,我建议使用withRouter

标签: reactjs redux react-router


【解决方案1】:

你也可以使用react router dom库useHistory;

import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

https://reactrouter.com/web/api/Hooks/usehistory

【讨论】:

    【解决方案2】:

    最简单的方法之一:使用Link如下:

    import { Link } from 'react-router-dom';
    
    <Link to={`your-path`} activeClassName="current">{your-link-name}</Link>
    
    

    如果我们想将整个 div 部分作为链接覆盖:

     <div>
         <Card as={Link} to={'path-name'}>
             .... 
               card content here
             ....
         </Card>
     </div>
    
    

    【讨论】:

      【解决方案3】:

      您也可以在Route 中使用Redirect,如下所示。这是为了处理无效路由。

      <Route path='*' render={() => 
           (
             <Redirect to="/error"/>
           )
      }/>
      

      【讨论】:

        【解决方案4】:

        实际上这取决于您的用例。

        1) 您希望保护您的路线免受未经授权的用户的访问

        如果是这种情况,您可以使用名为&lt;Redirect /&gt; 的组件并可以实现以下逻辑:

        import React from 'react'
        import  { Redirect } from 'react-router-dom'
        
        const ProtectedComponent = () => {
          if (authFails)
            return <Redirect to='/login'  />
          }
          return <div> My Protected Component </div>
        }
        

        请记住,如果您希望 &lt;Redirect /&gt; 以您期望的方式工作,您应该将它放在组件的渲染方法中,以便最终将其视为 DOM 元素,否则它将无法工作。

        2) 你想在某个动作之后重定向(比如说在创建一个项目之后)

        在这种情况下,您可以使用历史记录:

        myFunction() {
          addSomeStuff(data).then(() => {
              this.props.history.push('/path')
            }).catch((error) => {
              console.log(error)
            })
        

        myFunction() {
          addSomeStuff()
          this.props.history.push('/path')
        }
        

        为了访问历史记录,您可以使用名为 withRouter 的 HOC 包装您的组件。当你用它包装你的组件时,它会传递 match locationhistory 属性。更多详情请查看withRouter的官方文档。

        如果您的组件是&lt;Route /&gt; 组件的子组件,即如果它类似于&lt;Route path='/path' component={myComponent} /&gt;,则您不必用withRouter 包装您的组件,因为&lt;Route /&gt; 传递match,@ 987654337@ 和 history 给它的孩子。

        3) 点击某个元素后重定向

        这里有两个选项。您可以通过将history.push() 传递给onClick 事件来使用它:

        <div onClick={this.props.history.push('/path')}> some stuff </div>
        

        或者您可以使用&lt;Link /&gt; 组件:

         <Link to='/path' > some stuff </Link>
        

        我认为这种情况下的经验法则是首先尝试使用&lt;Link /&gt;,我想尤其是因为性能。

        【讨论】:

        • 它对我有用 `this.props.history.push("/");` React-router--v4.2 谢谢@Cagri
        • stackoverflow.com/questions/60579292/…你能看看这个qs吗?
        • 在最后一个选项中,因为组件的props中有history才能做到this.props.history.push('/path'),这意味着该组件是&lt;Route/&gt;的子组件或者它有withRouter wrapper出口正确吗?
        • 所以可以在不指定&lt;Route path='/path' component={Comp}/&gt;的情况下路由到另一个组件,我猜只是在一个条件下简单的render() { return &lt;Comp/&gt;}
        • @Andre 是的,使用this.props.history 是正确的,但是我不确定我的第二个问题是否正确? route to another component 到底是什么意思?
        【解决方案5】:

        现在使用 react-router v15.1 及以后我们可以 useHistory 挂钩,这是超级简单明了的方法。这是源博客中的一个简单示例。

        import { useHistory } from "react-router-dom";
        
        function BackButton({ children }) {
          let history = useHistory()
          return (
            <button type="button" onClick={() => history.goBack()}>
              {children}
            </button>
          )
        }
        

        您可以在任何功能组件和自定义挂钩中使用它。 是的,这不适用于与任何其他钩子相同的类组件。

        在此处了解更多信息https://reacttraining.com/blog/react-router-v5-1/#usehistory

        【讨论】:

          猜你喜欢
          • 2011-10-31
          • 1970-01-01
          • 1970-01-01
          • 2018-12-21
          • 2011-11-02
          • 2012-04-28
          • 2018-05-24
          • 2017-11-23
          • 1970-01-01
          相关资源
          最近更新 更多