首页 > 解决方案 > React:无法对未安装的组件执行反应状态更新。使用`useLocation()`时

问题描述

所以这是我的问题。我有:

const nav = useHistory();
const location = useLocation();

location用于确定其类的 DOM。

<IonItem className={location.pathname === appPage.url ? 'selected' : ''} routerLink={appPage.url} routerDirection="none" lines="none" detail={false}>

然后当我打电话时:

nav.push('/');

它产生错误:

index.js:1 警告:无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要解决此问题,请在 useEffect 清理函数中取消所有订阅和异步任务。

如果我跟踪它,useLocation()当我调用nav.push('/'). 这会触发 DOM 更新<IonItem>以检查className.

我怎样才能防止这种情况?


代码

const Menu: React.FC = () => {
    
    const location = useLocation();
    const nav = useHistory();

    const logout = () => {
        nav.push('/');
    }

    return (
        <div>
            <h3 className={location.pathname === '/account' ? 'selected' : ''}>Title</h3>
            <button onClick={logout}>Logout</button>
        </div>
    )

}

export default Menu;

nav.push('/')会产生问题,因为它会更改location触发 DOM 更新的内容。

标签: reactjsreact-nativereact-routerreact-hooks

解决方案


尝试跟踪已安装组件的引用。

const Menu: React.FC = () => {
    
    const location = useLocation();
    const nav = useHistory();

    // Use a ref to maintain the mounted state across component re-renders 
    const mountedRef = useRef(false);

    // just for tracking mounted state
    useEffect(() => {
        mountedRef.current = true;
        return () => {
            mountedRef.current = false;  
        }
    }, [])

    const logout = () => {
        if(mountedRef.current) {
            nav.push('/');
        }
    }

    return (
        <div>
            <h3 className={location.pathname === '/account' ? 'selected' : ''}>Title</h3>
            <button onClick={logout}>Logout</button>
        </div>
    )

}

export default Menu;

来源:https ://www.benmvp.com/blog/handling-async-react-component-effects-after-unmount/


推荐阅读