在 Next.js 中有条件地执行 'getInitialProps'

Conditional execution of 'getInitialProps' in Next.js

我使用 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。我如何在 getInitialProps 中使用 useContext

我正在寻找的是一种防止组件向其发送冗余身份验证请求的方法 服务器。

如果能有一些条件执行的方法就好了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 {};

};

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