更新:2022 年:使用 useNavigate 反应 Router v6.6.1
The useHistory()
hook 现已弃用。如果您使用的是 React Router 6,以编程方式导航的正确方法如下:
import { useNavigate } from "react-router-dom";
function HomeButton() {
const navigate = useNavigate();
function handleClick() {
navigate("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
带钩子的 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,您可以采用三种方法在组件内进行编程路由。
- Use the
withRouter
高阶分量。
- 使用合成并渲染
<Route>
- Use the
context
.
React Router 主要是一个包装器history https://github.com/ReactTraining/history图书馆。history
处理与浏览器的交互window.history https://developer.mozilla.org/en-US/docs/Web/API/Window/history为您提供浏览器和哈希历史记录。它还提供内存历史记录,这对于没有全局历史记录的环境非常有用。这在移动应用程序开发中特别有用(react-native
)并使用 Node.js 进行单元测试。
A history
实例有两种导航方法:push
and replace
。如果你想到history
作为访问过的位置的数组,push
将向数组添加一个新位置并且replace
将用新位置替换数组中的当前位置。通常您会想要使用push
导航时的方法。
在 React Router 的早期版本中,您必须创建自己的history
实例,但在 v4 中<BrowserRouter>
, <HashRouter>
, and <MemoryRouter>
组件将为您创建浏览器、哈希和内存实例。 React Router 使得属性和方法history
与您的路由器关联的实例可通过上下文在router
object.
1. 使用withRouter
高阶分量
The withRouter
高阶组件将注入history
对象作为组件的支柱。这允许您访问push
and replace
方法,而无需处理context
.
import { withRouter } from 'react-router-dom'
// this also works with react-router-native
const Button = withRouter(({ history }) => (
<button
type='button'
onClick={() => { history.push('/new-location') }}
>
Click Me!
</button>
))
2. 使用合成并渲染<Route>
The <Route>
组件不仅仅用于匹配位置。您可以渲染无路径路线并它将始终与当前位置匹配. The <Route>
组件传递相同的 propswithRouter
,这样您就可以访问history
方法通过history
prop.
import { Route } from 'react-router-dom'
const Button = () => (
<Route render={({ history}) => (
<button
type='button'
onClick={() => { history.push('/new-location') }}
>
Click Me!
</button>
)} />
)
3. 使用上下文*
但你可能不应该
最后一个选项只有在您觉得使用 React 很舒服时才应该使用context https://facebook.github.io/react/docs/context.html模型(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 component
Button.contextTypes = {
history: React.PropTypes.shape({
push: React.PropTypes.func.isRequired
})
}
1 和 2 是最简单的实施选择,因此对于大多数用例来说,它们是您的最佳选择。