[英]Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component
App.js:应用程序.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: 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身份验证.js
export const Auth = async () => {
const dispatch = useDispatch();
// some logic for authentication and authorization to get the user
dispatch(setUser(userId));
}
Received error收到错误
Uncaught (in promise) Error: Invalid hook call.
未捕获(承诺)错误:无效的钩子调用。 Hooks can only be called inside of the body of a function component.
钩子只能在函数组件的主体内部调用。
at auth.js:在 auth.js:
const dispatch = useDispatch();
Why do I get this error and how to solve this?为什么会出现此错误以及如何解决?
Hooks cannot be called inside plain javascript functions, only within another hooks, or in function components.不能在普通的 javascript 函数中调用钩子,只能在另一个钩子或函数组件中调用。
Reference: https://reactjs.org/docs/hooks-rules.html参考: https : //reactjs.org/docs/hooks-rules.html
I solved this by moving the const dispatch = useDispatch();
我通过移动
const dispatch = useDispatch();
解决了这个问题const dispatch = useDispatch();
up to App.js and pass the dispatch var as an argument to the method needs it.直到 App.js 并将 dispatch var 作为参数传递给需要它的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.