【发布时间】:2020-05-31 00:45:29
【问题描述】:
我使用useContext 和useReducer 进行全局状态管理我想检查用户是否经过身份验证。为此,我想到的是以这种方式检查getInitialProps内部:
DashboardPage.getInitialProps = async () => {
const [globalState, dispatch] = useContext(STORE.storeContext);
let auth = globalState.isAuthed
if (!auth) {
auth = axiox.get('/authenticateThisUser');
}
return {
auth,
}
}
但是,当我执行这个 sn-p 时,它会抛出 Error: Invalid hook call. Hooks can only be called inside of the body of a function component。如何在getInitialProps 中使用useContext?
我正在寻找的是一种防止组件向其发送冗余身份验证请求的方法 服务器。
如果有条件执行getInitialProps的方法就好了
像这样:
if(globalState.isAuthed){
//dont execute getInitialProps of this component
}else {
//execute getInitialProps of this component
}
【问题讨论】:
-
react 钩子只能在函数式组件内部使用,不能在函数、循环或块内部使用。阅读文档以获取更多信息。在这里,您正在创建 const [globalState, dispatch] = useContext(STORE.storeContext) ;函数内部的上下文挂钩,而不是功能组件。
标签: react-hooks next.js