【问题标题】:Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component未捕获(承诺中)错误:无效的挂钩调用。 Hooks 只能在函数组件的主体内部调用
【发布时间】:2021-11-17 07:23:46
【问题描述】:

App.js:

function App() {
  PreProcess();
  const user = useSelector(selectUser);   // user initialized to null
  return user ?
    (
      <p>{user}</p>
    )
    :
    (<p>Authenticating and Authorizing</p>)
}

export default App;

preProcess.js:

export const PreProcess = async () => {
    await readEnvVars();  // read env vars in local json file
    Auth();   // need environment variables for authentication and authorization
}

auth.js

export const Auth = async () => {
    const dispatch = useDispatch();

    // some logic for authentication and authorization to get the user

    dispatch(setUser(userId));
}

收到错误

未捕获(承诺中)错误:无效的挂钩调用。钩子只能是 在函数组件的主体内部调用。

在 auth.js:

const dispatch = useDispatch();

为什么会出现此错误以及如何解决?

【问题讨论】:

    标签: javascript reactjs async-await react-hooks redux-toolkit


    【解决方案1】:

    我通过将 const dispatch = useDispatch(); 移动到 App.js 并将 dispatch var 作为参数传递给需要它的方法来解决这个问题。

    【讨论】:

      【解决方案2】:

      不能在普通的 javascript 函数中调用钩子,只能在另一个钩子或函数组件中调用。

      参考:https://reactjs.org/docs/hooks-rules.html

      【讨论】:

      • 我记得我收到了这个警告,所以我把函数名改成了大写,让它成为一个 React 函数组件,警告就消失了。无论如何,它不起作用,有什么解决方法的建议吗?
      • Auth 不是函数组件或钩子,所以你的代码不起作用。
      猜你喜欢
      • 2021-01-16
      • 1970-01-01
      • 2020-07-22
      • 2020-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      相关资源
      最近更新 更多