【问题标题】:Cant use a useDispatch inside a useEffect不能在 useEffect 中使用 useDispatch
【发布时间】:2021-10-01 08:34:09
【问题描述】:

所以我在 useEffect 中使用 useDispatch 时收到以下错误

第 58:5 行:React Hook "useDispatch" 不能在内部调用 打回来。必须在 React 函数组件中调用 React Hooks 或 一个自定义的 React Hook 函数 react-hooks/rules-of-hooks

我有一个如下组件

import { useSelector, useDispatch } from 'react-redux';
import { myModules } from '#/redux/modules';

const Component = () => {
 const images = useSelector(getImages)

  useEffect( () =>  {
    useDispatch(myModules.actions.setMaskVisible(true));
  }, [images]);

}

setMaskVisible 差不多

export const SET_MASK_VISIBLE = 'caps/SET_MASK_VISIBLE';
const setMaskVisible = payload => {
  return {
    type: SET_MASK_VISIBLE,
    payload
  };
};

export default { setMaskVisible }

我基本上是在图像更新时尝试更改 redux 值。为什么它不起作用?

【问题讨论】:

    标签: reactjs redux react-hooks


    【解决方案1】:

    看看documentation。你调用 useDispatch 来获取一个函数并调用 that 函数:

    import { useSelector, useDispatch } from 'react-redux';
    import { myModules } from '#/redux/modules';
    
    const Component = () => {
     const images = useSelector(getImages)
     const dispatch = useDispatch();
    
      useEffect( () =>  {
        dispatch(myModules.actions.setMaskVisible(true));
      }, [images]);
    
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-13
      • 2020-04-24
      • 2023-04-03
      • 2020-04-08
      • 2020-09-13
      • 1970-01-01
      • 2020-01-11
      • 2021-01-04
      • 2020-09-06
      相关资源
      最近更新 更多