【问题标题】:How to use conditional operator in react js [duplicate]如何在反应js中使用条件运算符[重复]
【发布时间】:2020-01-07 14:59:52
【问题描述】:

在很多地方,我设置的都是由 etc 修改、创建的:

const test = this.state.isValueEdited
? {
  modifiedById: getLoggedInUser().userId,
}
: {
 // TODO
};

我如何检查getLoggedInUser 是否有一些价值,而不是访问.userId.. 否则让我们设置null

谢谢

干杯

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    也使用ternary operator

     modifiedById: getLoggedInUser() ? getLoggedInUser().userId : null
    

    为了避免执行两次

    const evaluation = getLoggedInUser()
    
    {modifiedById: evaluation ? evaluation.userId : null}
    

    【讨论】:

    • 这将调用getLoggedInUser() 两次。那是低效的,可能会导致不必要的 sife 效应。
    【解决方案2】:

    你可以使用逻辑或||

    modifiedById: ( getLoggedInUser() || { userId: null } ).userId
    

    当 getLoggedInUser 返回的值返回假值时,{userId : null} 将作为默认值

    这期望从 getLoggedUser 返回的值是假值,以防它不满足条件

    【讨论】:

    • 您能解释一下这一行吗getLoggedInUser() || { userId: null } 这意味着即使 userId 为 null 也尝试访问它?还是?
    • 整洁!不是这种语法的最大粉丝,但它确实可以完成工作
    • @Roxy'Pro 当从getLoggedInUser 返回的值是假的时,只有{userId: null} 会出现,逻辑或从左边开始计算表达式,一旦找到真值就停止,如果没有的值为 true 它返回表达式的最后一个值,所以这里在 getLoggedInUser 返回虚假值,而不是仅使用 {userId: null} 否则将使用从函数返回的值
    • 否决选民关心评论:/
    【解决方案3】:

    您可以先检索用户,然后您可以使用&& 运算符获取userId,前提是user 返回truthy。 falsenullundefined""、0、NaN 是假值

    const user = getLoggedInUser() || null;
    
    const test = this.state.isValueEdited ? ({
      modifiedById: user && user.userId,
    }) : ...
    

    如果getLoggedInUser在用户未登录时已经返回null,则可以省略|| null

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-21
      • 1970-01-01
      • 2020-07-21
      • 2012-03-14
      • 1970-01-01
      • 2021-04-22
      • 1970-01-01
      相关资源
      最近更新 更多