react路由history信息获取
React 路由提供了一些不同的方法来访问和使用历史记录对象。
1. 使用 useHistory Hook。
react router v6 文档使用 useHistory Hook 可以获取历史记录对象。首先,在组件中导入来自 react-router-dom 的 useHistory Hook:
import { useHistory } from "react-router-dom";。
然后在组件中调用 useHistory Hook 并存储返回对象:
const history = useHistory();。
现在,您可以使用 history 对象访问历史记录,例如:
history.push("/example");。
2. 使用 withRouter 高阶组件。
使用 withRouter 高阶组件可以将路由对象作为 props 传递给组件。首先,在组件中导入 withRouter:
import { withRouter } from "react-router-dom";。
然后使用 withRouter 包装组件:
// some code。
};。
现在,您可以使用 this.props.history 访问历史记录。例如:
this.props.history.push("/example");。