reactjs - 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 更新的内容。
解决方案
尝试跟踪已安装组件的引用。
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/
推荐阅读
- angular - $localize 在 Angular 中使用条件语句
- database - 一张发票给多个访问中的客户
- java - Java Brick Breaker Game 桨留下痕迹
- c# - .Netstandard 中的 PictureBox.Handle
- sql - 为什么时间戳列在红移中返回空值?
- python - joblib 和 Brute-Force PDF Password Breaker 自动化无聊的东西
- python - 如何处理网页抓取中缺少元素的网页?请参阅下面的代码
- python-3.x - 无法引用 Django 模板
- quarkus - Quarkus Reactive with Vert.x and Hibernate Reactive / java.lang.NullPointerException:无法存储到对象数组,因为“this.loadedState”为空
- node.js - 在节点js中动态创建一个json