无法解构 null 的属性

Mik*_*e K 9 javascript destructuring ecmascript-6 reactjs

我有一个组件可以user从它的authprop中解构:

 const Profile = ({
     auth: {user}
 }) => {...}
Run Code Online (Sandbox Code Playgroud)

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

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

Pat*_*rts 6

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

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

const Profile = ({ auth }) => {
  const user = auth && auth.user;
  ...
}
Run Code Online (Sandbox Code Playgroud)