无法解构 null 的 属性

Cannot destructure property of null

我有一个组件从其 auth 属性中解构 user

 const Profile = ({
     auth: {user}
 }) => {...}

问题是,当我在开发时,每当我保存任何更改时,Nodemon 都会不断刷新我的页面。当组件尝试挂载时,它会抛出一个错误,指出它无法从 auth 中解构 user,因为此时 auth 为空(直到我浏览该站点并重新登录) .

有没有一种优雅的方式来处理这个问题?我看了一下 this article,但我不能做 const { user } = auth || {} 之类的事情。嗯..我的意思是,我可以,但我想从道具中解构,而不是在函数体中做 const { user } = auth || {}

authnull 时,无法使用具有解构语法的默认参数来解析 user 而不抛出 TypeError.

只需解构为 auth 并检查它是否为真:

const Profile = ({ auth }) => {
  const user = auth && auth.user;
  ...
}