带有钩子的React Router v5.1.0
useHistory如果您使用React> 16.8.0和功能组件,则React Router> 5.1.0中会有一个新的钩子。
import { useHistory } from "react-router-dom";function HomeButton() { const history = useHistory(); function handleClick() { history.push("/home"); } return ( <button type="button" onClick={handleClick}> Go home </button> );}反应路由器v4
使用React Router v4,您可以采用三种方法在组件内进行编程路由。
- 使用
withRouter
高阶组件。 - 使用合成并渲染
<Route>
- 使用
context
。
React
Router主要是
history库的包装器。
history通过浏览
window.history器和哈希历史记录为您处理与浏览器的交互。它还提供了内存历史记录,这对于没有全局历史记录的环境很有用。这在移动应用程序开发(
react-native)和使用Node进行单元测试中特别有用。
一个
history实例有用于导航两种方法:
push和
replace。如果您将
history视为已访问位置的数组,
push则将一个新位置添加到该数组中,
replace并将该数组中的当前位置替换为新位置。通常,您将
push在导航时使用该方法。
在早期版本的阵营路由器,你必须创建自己的
history实例,但在第4版的
<BrowserRouter>,
<HashRouter>和
<MemoryRouter>组件将创建一个浏览器,哈希和内存的实例为您服务。React
Router
history通过
router对象下的上下文使与路由器关联的实例的属性和方法可用。
1.使用withRouter
高阶成分
的
withRouter高次成分将注入的
history对象作为所述部件的支柱。这样一来,您无需处理即可访问
push和
replace方法
context。
import { withRouter } from 'react-router-dom'// this also works with react-router-nativeconst Button = withRouter(({ history }) => ( <button type='button' onClick={() => { history.push('/new-location') }} > Click Me! </button>))2.使用合成并渲染 <Route>
该
<Route>组件不仅用于匹配位置。您可以渲染无路径路线,并且 该 路线 将始终与当前位置匹配
。该
<Route>组件传递与相同的道具
withRouter,因此您将能够
history通过
history道具访问方法。
import { Route } from 'react-router-dom'const Button = () => ( <Route render={({ history}) => ( <button type='button' onClick={() => { history.push('/new-location') }} > Click Me! </button> )} />)3.使用上下文*
但是你可能不应该
最后一个选项是只有在您熟悉使用React的上下文模型时才应使用的选项(React的Context
API从v16开始是稳定的)。
const Button = (props, context) => ( <button type='button' onClick={() => { // context.history.push === history.push context.history.push('/new-location') }} > Click Me! </button>)// you need to specify the context type so that it// is available within the componentButton.contextTypes = { history: React.PropTypes.shape({ push: React.PropTypes.func.isRequired })}1和2是最简单的实现方法,因此对于大多数用例来说,它们是最好的选择。



