【问题标题】:Use router from getServerSideProps使用来自 getServerSideProps 的路由器
【发布时间】:2023-01-19 18:21:43
【问题描述】:

我想要实现的是,如果他的令牌已过期,则将用户重定向到登录页面。

在 getServerSideProps 中,我向服务器发送一个获取请求以接收一些数据,如果我得到数据,我想将这些数据作为我的页面的道具提供,但如果它是未经授权的,我想将用户重定向到登录页面,但似乎我可以当我尝试出现此错误时,不要在 getServerSideProps 中调用 useRouter

React Hook“useRouter”在函数“getServerSideProps”中被调用,它既不是 React 函数组件也不是自定义 React Hook 函数。 React 组件名称必须以大写字母开头。 React Hook 名称必须以单词“use”开头。eslint

这是我的代码

export async function getServerSideProps({ req, params }) {
  const token = await getToken({ req });
  const userId = params.userId;
  const router = useRouter(); // the line with the error
  let result = {};

   await axiosPrivateWithToken(accessToken)
    .get(`/user/${userId}`)
    .then((res) => {
      result = res.data;
    })
    .catch((error) => {
      if(error.response.status == 401) {
      here where I want to use router.push('/login')
     }
    });

}

是否可以 ?如果是这样怎么办?!感谢您的时间

【问题讨论】:

标签: javascript reactjs next.js next-router


【解决方案1】:

您只能从function componentcustom React hook function调用hooks,因为它在错误中提到,因此无法从getServerSidePros内部使用next-router

然而你可以通过 redirect 键对象来实现

 .then((res) => {
      result = res.data;
  })
  .catch((error) => {
      if(error.response.status == 401) result = 'redirection'
  });

然后根据 result 的值决定要做什么:

if(result === 'redirection') {
return {
 redirect: {
   destination: "/login",
   permanent: false,
 }};
}else {
// what you are used to do
}

【讨论】:

    【解决方案2】:

    不可能在getServerSideProps 中使用useRouter。 相反,您可以返回 axiosPrivateWithToken 响应并将其作为 props 接收到您的组件上,并将其放入 useEffect 并在那里处理您的重定向逻辑。

    【讨论】:

    • 重定向客户端是不必要的,也是糟糕的用户体验。您可以使用context.res.writeHead(302, { Location: "/login" }) 重定向服务器端。
    猜你喜欢
    • 2020-12-19
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 2016-11-10
    • 2022-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多