react-hooks - Next.js 中“getInitialProps”的条件执行
问题描述
我有全局状态管理使用useContext
,useReducer
我想检查用户是否经过身份验证。为此,我想到的getInitialProps
是以这种方式检查内部:
DashboardPage.getInitialProps = async () => {
const [globalState, dispatch] = useContext(STORE.storeContext);
let auth = globalState.isAuthed
if (!auth) {
auth = axiox.get('/authenticateThisUser');
}
return {
auth,
}
}
但是,当我执行此代码段时,它会抛出Error: Invalid hook call. Hooks can only be called inside of the body of a function component
. 我如何useContext
在里面使用getInitialProps
?
我正在寻找的是一种防止组件向服务器发送冗余身份验证请求的方法。
如果有一些方法可以getInitialProps
像这样有条件地执行,那就太好了:
if(globalState.isAuthed){
//dont execute getInitialProps of this component
}else {
//execute getInitialProps of this component
}
解决方案
实际上我想要完成的可以使用下面的代码来完成:
DashboardPage.getInitialProps = async ({ req, query, asPath }) => {
// only in server-side
if (req) {
const userUrl = `http://localhost:3000${userConfig.ROUTES.user.getUser}`;
const isMeUrl = `http://localhost:3000${userConfig.ROUTES.isMe}`;
const result = await axios.all([axios.get(isMeUrl), axios.get(userUrl)]);
return {
me: result[0].data.payload,
user: result[1].data.payload,
};
}
// only in client-side
// since we've done authenticating, it is set in the global state management
// therefore, no need to send any request to the auth API endpoint.
return {};
};
这样,我们确保仅在服务器端(第一个请求)发送身份验证请求,并防止组件发送冗余请求。
推荐阅读
- python - 如何在两个日期之间的对象列表中搜索值python
- arrays - go语言中如何将带有map的struct存储到数组中
- python - 如何按日期范围汇总总和并加入
- java - 想要制作从动态创建的editTexts中获取值的按钮
- angular - 为什么按键事件在两个输入中不起作用?
- javascript - 在 v-for 中绑定不同的事件监听器
- android - 更改 LiveData 时 DataBinding 不更新值
- selenium - Python selenium 将表值获取到列表列表中
- php - 创建 Laravel 项目
- javascript - commonjs和es6模块的去重