首页 > 解决方案 > Next.js 中“getInitialProps”的条件执行

问题描述

我有全局状态管理使用useContextuseReducer我想检查用户是否经过身份验证。为此,我想到的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
}

标签: react-hooksnext.js

解决方案


实际上我想要完成的可以使用下面的代码来完成:

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 {};

};

这样,我们确保仅在服务器端(第一个请求)发送身份验证请求,并防止组件发送冗余请求。


推荐阅读