如何使用 React 钩子和 Redux 从 useEffect 执行 store.unsubscribe [英] How to execute store.unsubscribe from useEffect using React hooks and Redux

查看:38
本文介绍了如何使用 React 钩子和 Redux 从 useEffect 执行 store.unsubscribe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 redux 和 hooks 的 React 无状态组件.我需要在页面加载时显示项目数 (useEffect) 并在每次添加或删除项目时更新它 (store.subscribe)

I have a React stateless component using redux and hooks. I need to display the number of items on page load (useEffect) and update it every time I add or remove an item (store.subscribe)

useEffect(() => {
    setState({
        items: store.getState().items.length
    });
}, []);

store.subscribe(() => {
    setState({
        items: store.getState().items.length
    });
});

但这会导致控制台显示警告无法对卸载的组件执行 React 状态更新.这是一个空操作,但它表明您的应用程序中存在内存泄漏.要解决此问题,请取消 useEffect 清理函数中的所有订阅和异步任务..

but this is causing the console to display the warning Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. .

如何从 useEffect 内部取消订阅?

How can I unsubscribe from inside useEffect?

推荐答案

如果将 useEffect 调用的第二个参数设置为 [],则效果回调函数将充当 ComponentDidMount.如果该回调函数返回一个函数,则该函数将在组件卸载前调用 (ComponentWillUnmount).

If you set the second parameter of useEffect call to [], the effect callback function would act as ComponentDidMount. If that callback function returns a function, this function will be called just before the component is unmounted(ComponentWillUnmount).

我想这个 setState 应该用 setItems 替换,如下所示.请试试这个代码.

And I guess this setState should be replaced with setItems as below. Please try this code.

const [items, setItems] = useState([]);
useEffect(() => {
    setItems(store.getState().items.length);
    
    
    const unsubscribe = store.subscribe(() => {
        setItems(store.getState().items.length);
    });
    
    return unsubscribe;
}, []);

这篇关于如何使用 React 钩子和 Redux 从 useEffect 执行 store.unsubscribe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆