在 JS 中描述对象 {data: {user: {id, role}}} = useSession() throw an erorr

问题描述 投票:0回答:1

一个可以初始化为undefined的JS中的对象怎么解构。例如,我需要解构 useSession 钩子返回的会话对象。

如果我这样写:

{data: {user: {id, role}}} = useSession()

如果 useSession 返回 undefined | null 然后它抛出一个错误。

我所能做的就是在 JSX 中这样写 data?.user?.role === 'admin' ...

如果数据 == undefined,我可以这样写而不会出现错误吗?

{data: {user: {id, role}}} = useSession()

destructuring next-auth
1个回答
0
投票

将此组件添加到您的 app.js 文件中:

function Auth({ children }) {
  const router = useRouter();
  const { status } = useSession({
    required: true,
    onUnauthenticated() {
      router.push("/sign-in");
    },
  });

  if (status === "loading") {
    return 
      <div>
       Loading...
      </div>
  }
  return children;
}

然后将

auth
属性添加到您需要定义
session
的每个页面,否则用户将被重定向到
/sign-in

示例:

const Page = () => {
//...
}
Page.auth={}

最后在

MyApp
组件中返回
<Component {...pageProps} />
条件:

{
  Component.auth ? (
    <Auth>
      <Component {...pageProps} />
    </Auth>
  ) : (
    <>
      <Component {...pageProps} />
    </>
  );
}

这将使用

auth
组件包装具有
<Auth>
属性的每个页面,后者将为它完成工作,因此
session
将始终被定义

© www.soinside.com 2019 - 2024. All rights reserved.