简体   繁体   English

如果有 IF 要路由,为什么 React / NextJS 仍然呈现返回?

[英]Why does React / NextJS still render the return if there is an IF to route?

I'm working on a web app in NextJS.我正在 NextJS 中开发一个网络应用程序。 I have some logic that will check if a user is logged in, else route to the login page.我有一些逻辑可以检查用户是否登录,否则路由到登录页面。

But in reality this code actually returns an error where the userContext cannot be defined.但实际上,这段代码实际上返回了一个错误,其中userContext无法定义。 That's why I have a check for a user first.这就是为什么我首先检查用户。

I hypothesis the return statement is being run despite the verification for existing user.我假设尽管对现有用户进行了验证,但return语句仍在运行。 Is this true of React? React 是这样吗?

TypeError: Cannot read properties of null (reading 'displayName')

Full-ish code:完整的代码:

... some imports and stuff

export default function Account(pageProps) {
  const route = useRouter()
  const userContext = useUserContext()

  if (!userContext) {
    route.push("/login")
  } 

  return (
      <Box sx={{ mt: "3rem" }}>
        {user &&
          <Typography variant="h2">
            Welcome{userContext.displayName && ' ' + userContext.displayName}!
          </Typography>
        }
      </Box>
  )

NOTE: I resolved this issue by adding a return statement in the IF statement.注意:我通过在 IF 语句中添加return语句解决了这个问题。 But I still would like to know why this happens.但我仍然想知道为什么会这样。

try this function to determine whether object or anything is empty or not :试试这个函数来确定对象或任何东西是否为空:

// custom function to check if an object / array or some variable is empty
export const isEmpty = ( value ) =>
  value === undefined ||
  value === null ||
  ( typeof value === "object" && Object.keys( value ).length === 0 ) ||
  ( typeof value === "string" && value.trim().length === 0 );

Then use it as following :然后按如下方式使用它:

  if (userContext && isEmpty(userContext)) {
    return route.push("/login");
  }
....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM