【问题标题】:Conditional execution of 'getInitialProps' in Next.jsNext.js 中“getInitialProps”的条件执行
【发布时间】:2020-05-31 00:45:29
【问题描述】:

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


【解决方案1】:

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

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

};

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-12
    • 2019-10-04
    • 2018-08-24
    • 2019-03-01
    • 2021-03-14
    • 1970-01-01
    • 2017-04-14
    • 2020-04-24
    相关资源
    最近更新 更多