【问题标题】:Why I can't use dispatch a thunk inside useEffect?为什么我不能在 useEffect 中使用 dispatch a thunk?
【发布时间】:2021-11-13 11:30:45
【问题描述】:

内部thunks.js

export const displayAlert = (text) => () => {   alert(`${text}`); }

在另一个文件中

const dispatch = useDispatch();

const example = () => {    
    useEffect(
        ()=>{dispatch(displayAlert('Hello'))}
        ) }

给我看

未捕获的错误:无效的挂钩调用

【问题讨论】:

  • 钩子只能在功能组件内部或另一个钩子内部使用,即自定义钩子。您可能打算在 example() 函数中调用 useDispatch

标签: reactjs redux redux-thunk


【解决方案1】:

useDispatch 钩子移动到组件中,并用大写字母重命名(以免触发另一个 lint 警告):

const Example = () => {
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(displayAlert("Hello"));
  });
};

rules of hooks

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 2021-05-11
    • 2021-06-07
    • 1970-01-01
    • 2020-04-29
    • 2018-05-26
    • 1970-01-01
    相关资源
    最近更新 更多