React中使用mouse-follower路由切换后悬浮图片未消失的问题
解决mouse-follower在React路由跳转后残留的问题
问题核心是React单页路由跳转时,原页面的mouse-follower实例未被销毁,导致它仍在全局DOM中生效,所以会在新页面继续显示悬浮图片。下面是几种可行的解决方法:
方法1:组件卸载时销毁mouse-follower实例
在你的主页组件中,用useEffect初始化mouse-follower,并在组件卸载时调用实例的destroy()方法清理资源:
import { useEffect } from 'react'; import MouseFollower from 'mouse-follower'; const HomePage = () => { useEffect(() => { // 初始化mouse-follower实例 const cursorInstance = new MouseFollower(); // 组件卸载时销毁实例 return () => { cursorInstance.destroy(); }; }, []); // 原主页渲染代码 return ( <Link to="/details" state={{ title: title }} style={{ textDecoration: "none", color: "black" }}> <Box data-cursor-img={image}> <Box sx={{ my: "3rem", display: 'flex', flexDirection: "column", alignItems: 'center', justifyContent: 'center', height: '10vh', textDecoration: "none" }}> <Box sx={{ fontSize: "3rem" }}><i className={icon}></i></Box> <Typography sx={{ m: "1rem" }}>{title}</Typography> </Box> </Box> </Link> ); };
方法2:监听路由变化重置mouse-follower状态
如果mouse-follower是全局初始化的,可通过监听路由路径变化,在页面切换时强制重置或隐藏悬浮元素:
import { useEffect } from 'react'; import { useLocation } from 'react-router-dom'; import MouseFollower from 'mouse-follower'; const App = () => { const location = useLocation(); let cursorInstance = null; useEffect(() => { cursorInstance = new MouseFollower(); return () => cursorInstance.destroy(); }, []); // 路由切换时重置cursor状态 useEffect(() => { if (cursorInstance) { cursorInstance.$el.style.display = 'none'; cursorInstance.reset(); } }, [location.pathname]); return ( {/* 你的App路由结构 */} ); };
方法3:强化新页面的隐藏属性生效逻辑
在新页面组件中,通过useEffect给全局body添加隐藏属性,确保mouse-follower在新页面全局失效:
import { useEffect } from 'react'; import { useLocation } from 'react-router-dom'; const Otherpage = () => { const location = useLocation(); const title = location.state.title; useEffect(() => { // 页面挂载时给body添加隐藏标记 document.body.setAttribute('data-cursor', '-hidden'); return () => { // 页面卸载时移除标记 document.body.removeAttribute('data-cursor'); }; }, []); return ( <div data-cursor="-hidden"> {title} </div> ); }; export default Otherpage;
本质原因是React客户端路由跳转不会刷新整个页面,原页面的mouse-follower实例仍在监听全局鼠标事件,必须主动清理实例或重置状态,才能避免它在新页面继续响应。
内容的提问来源于stack exchange,提问作者MD. Istiak Shamim Shishir
相关产品推荐
相关产品推荐

