react 获取路由跳转历史记录
时间: 2023-08-18 21:07:53 浏览: 58
在 React 中,您可以使用 `useHistory` 钩子来访问路由跳转历史记录。`useHistory` 钩子能够让您访问 Router 组件的 history 对象,该对象用于管理浏览器历史记录。
以下是一个示例代码,展示了如何使用 `useHistory` 钩子来获取路由跳转历史记录:
```javascript
import { useHistory } from 'react-router-dom';
function MyComponent() {
const history = useHistory();
function goBack() {
history.goBack();
}
function goForward() {
history.goForward();
}
function goToRoute() {
history.push('/my-route');
}
return (
<div>
<button onClick={goBack}>后退</button>
<button onClick={goForward}>前进</button>
<button onClick={goToRoute}>跳转到路由</button>
</div>
);
}
```
在上面的代码中,我们使用 `useHistory` 钩子来获取 `history` 对象,并使用它的 `goBack` 和 `goForward` 方法来后退和前进浏览器历史记录。我们还使用 `push` 方法将用户导航到新的路由。
注意,`useHistory` 钩子只能在 `Router` 组件内部使用。如果您的组件不是 `Router` 的子组件,则需要使用其他方式来获取 `history` 对象。