React Router v6 如何监听同路由<Link>二次点击(页面已挂载场景)
问题根因
React Router v6 中点击指向当前已激活路由的 <Link> 组件时,默认不会触发对应页面组件的重新挂载,也不会触发无相关依赖的 useEffect 执行,所以你之前写的日志只会在页面首次挂载时输出一次。
解决方案
方案1:在侧边栏Link组件侧实现(推荐)
逻辑集中在菜单组件维护,不需要修改业务页面代码,适配二次点击激活菜单的场景:
import { Link, useLocation } from 'react-router-dom'; // 你的侧边栏组件 function SideMenu() { const currentPath = useLocation().pathname; const entityPath = '/entity'; const handleEntityLinkClick = () => { // 判断当前已处于目标路由时执行指定操作 if (currentPath === entityPath) { console.log('Entity 页面的Link被二次点击'); // 其他自定义操作写在这里 } } return ( <Link to={entityPath} onClick={handleEntityLinkClick}>Entity</Link> ) }
方案2:在Entity页面组件内部实现
如果逻辑需要耦合在页面内,可以监听全量location对象的变化(即使路径相同,重复点击Link会更新location.key,会触发依赖执行):
import { useEffect } from 'react'; import { useLocation } from 'react-router-dom'; function Entity() { const location = useLocation(); useEffect(() => { // 每次点击指向该路由的Link都会触发 console.log('Entity 对应的Link被点击'); }, [location]); // 必须依赖完整的location对象,不能只写location.pathname return <div>Entity 页面内容</div>; }
内容的提问来源于stack exchange,提问作者Bradmage
相关产品推荐
相关产品推荐

