Javascript 处理属性类型时出错

Javascript 处理属性类型时出错,javascript,Javascript,我收到一个错误TypeError:无法读取未定义的属性“id”,发生这种情况时,我希望返回null 有人知道最好的方法吗 const currenFolderId = this.state.currentFolder.id ? this.state.currentFolder.id : null; 尝试: const currenFolderId = this.state.currentFolder && this.state.currentFolder.id

我收到一个错误
TypeError:无法读取未定义的属性“id”
,发生这种情况时,我希望返回null

有人知道最好的方法吗

 const currenFolderId = this.state.currentFolder.id
    ? this.state.currentFolder.id
    : null;
尝试:

const currenFolderId = this.state.currentFolder && this.state.currentFolder.id
   ? this.state.currentFolder.id
   : null;
尝试:

const currenFolderId = this.state.currentFolder && this.state.currentFolder.id
   ? this.state.currentFolder.id
   : null;

这是有效的。我不明白你为什么需要这样做。state.currentfolder&。使用
this.state.currentfolder
检查
currentfolder
是否是
未定义的
-然后如果
currentfolder
具有
id
属性。这是有效的。我不明白你为什么需要这样做。state.currentfolder&
this.state.currentFolder
检查
currentFolder
是否为
undefined
-然后如果
currentFolder
具有
id
属性。当您具有类似
this.state.currentFolder.id
的链式访问权限时,如果链中不存在属性,则会失败:
this.state.currentFolder=未定义;console.log(this.state.currentFolder.id);//打字错误谢谢这很有意义当你拥有像
this.state.currentFolder.id
这样的链式访问权限时,如果链中不存在属性,它将失败并返回该错误:
this.state.currentFolder=未定义;console.log(this.state.currentFolder.id);//打字错误谢谢,这很有道理