React Router里Link和history.push


  • administrators

    React Router 让 React App变得不像是一个单页面应用程序了(Single Page App)。有了它我们可以把页面的一个component当做是一个单独的页面来呈现(render)。

    当我们用React Router定义好页面,例如:

    <Route exact path="/" component={Home} />
    <Route path="/about" component={About} />
    <Route path="/topics" component={Topics} />
    

    我可以用Link来跳转,比如:

    <ul>
       <li>
          <Link to="/">Home</Link>
       </li>
       <li>
          <Link to="/about">About</Link>
       </li>
       <li>
          <Link to="/topics">Topics</Link>
       </li>
    </ul>
    

    虽然我们也可以用<a>,但是<a>会造成不必要的页面重刷新,因此用<Link>要好很多。

    那history.push是做什么用的?比如你想通过点击一个按钮来跳转到另一页面,这时候<Link>就用不上了,因为它不是函数,不能在onClick事件里被调用。反之push是函数,我可以用它是用实现动态跳转。
    例子如下:

    handleSubmit(ev) {
      ev.preventDefault();
      if (this.formIsValid()) {
         this.props.history.push('/');
      }
    }
    

    ⚠️使用history.push, 你的组件必须被withrouter包裹(HOC) 或者装饰@decorator,如下:

    import { withRouter } from "react-router";
    withRouter(YourComponent); // HOC 包裹
    
    @withRouter //decorator 装饰
    class YourComponent extends Component{
    }