在 Reactjs 中使用 useEffect 卸载组件时执行调度功能

时间:2020-12-21 14:38:26

标签: reactjs use-effect dispatch

我想在组件卸载后对状态项执行分派。所以我尝试了这个:

const dispatch = useDispatch();
const store = useStore();
const state = store.getState();
useEffect(() => {
    return () => {
       /* dispatch on state items code goes here */
    };
  }, []);

但是执行上述操作,我无法访问状态和调度。所以我在 useEffect 的依赖列表中添加了这两个,即 state 和 dispatch。现在我的代码是:

const dispatch = useDispatch();
const store = useStore();
const state = store.getState();
useEffect(() => {
    return () => {
       /* dispatch on state items code goes here */
    };
  }, [dispatch, state]);

但现在的问题是调度发生在每次状态更改时。我不希望在状态更改时发生调度。我希望它仅在组件卸载时发生。

请给点建议!

0 个答案:

没有答案