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);//打字错误代码>谢谢,这很有道理