在将其属性之一分配给变量之前检查对象在反应中不为 null 的正确方法是什么
what is the right way to check that an object is not null in react before assigning one of its properties to a variable
在 React 中,当组件更新时,对象从 null 变为预期内容是很常见的。这是一个动态过程,每次您将 属性 从这些对象分配给另一个变量时都会产生错误。
假设用户是将从 null 变为实际用户对象的对象,并且我想从用户中提取 属性 uid:
const uid = user.uid
当我尝试执行此操作时,如果用户为空,这可能会在反应中触发致命错误。
我试过使用:
user && const uid = user.uid
,但根本不起作用
这样做的正确方法是:
const uid = user && user.uid
有什么意见/建议吗?
?.运算符就像 .链接运算符,除了如果引用为空(null 或未定义)时不会导致错误,表达式 short-circuits 的 return 值为 undefined
所以这样做
const uid = user?.uid // will be undefined if not there else the actually value
在 React 中,当组件更新时,对象从 null 变为预期内容是很常见的。这是一个动态过程,每次您将 属性 从这些对象分配给另一个变量时都会产生错误。
假设用户是将从 null 变为实际用户对象的对象,并且我想从用户中提取 属性 uid:
const uid = user.uid
当我尝试执行此操作时,如果用户为空,这可能会在反应中触发致命错误。
我试过使用:
user && const uid = user.uid
,但根本不起作用
这样做的正确方法是:
const uid = user && user.uid
有什么意见/建议吗?
?.运算符就像 .链接运算符,除了如果引用为空(null 或未定义)时不会导致错误,表达式 short-circuits 的 return 值为 undefined
所以这样做
const uid = user?.uid // will be undefined if not there else the actually value