You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Router DOM v6中useHistory替代:实现history.listen功能

在React Router v6中替代history.listen的实现方案

React Router v6移除了useHistory钩子,要实现路由变化监听的功能,我们可以借助useLocation和useEffect的组合来完成,具体修改如下:

export default () => {
    const ref = useRef(null);
    const location = useLocation();
    const navigate = useNavigate();

    useEffect(() => {
        const { onParentNavigate } = mount(ref.current, {
            onNavigate: ({ location }: any) => {
                navigate(location.pathname);
            },
        });

        // 首次加载时触发一次回调,对齐history.listen的初始行为
        onParentNavigate(location);

        // 若onParentNavigate内部有需要清理的监听逻辑,可在此返回清理函数
        return () => {
            // 示例:如果onParentNavigate返回了取消监听的方法,可在此调用
            // onParentNavigate.cleanup?.();
        };
    }, [location, navigate]); // 依赖location,路由变化时自动触发回调

    return (
        <div ref={ref} />
    )
}

关键说明

  • 核心逻辑:通过useLocation获取当前路由的location对象,当路由发生变化时,location会生成新的引用,触发useEffect执行,此时调用onParentNavigate并传入最新路由信息,以此替代history.listen的监听效果。
  • 清理机制:如果你的onParentNavigate函数内部注册了额外的监听或占用了资源,记得在useEffect的返回函数中执行清理操作,避免内存泄漏。
  • 首次触发:主动调用onParentNavigate(location)确保初始路由状态能被正确处理,和history.listen的初始行为保持一致。

内容的提问来源于stack exchange,提问作者Pradeep

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 17:42:03