使用React Router重定向页面的最佳方法是什么?

reactjs React.js

凯梅小胖

2020-03-13

我是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")详细信息:如何在React Router v4中推送到历史记录?

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

第1394篇《使用React Router重定向页面的最佳方法是什么?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
null 2020.03.13

现在有了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

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android