【问题标题】:If - else if statement - JavaScriptIf - else if 语句 - JavaScript
【发布时间】:2021-09-11 20:56:26
【问题描述】:

我是编码新手,我对道具的 if - else if 语句有疑问

下面的代码 sn-p 可以工作,但是我想在 props 中添加另一个属性,如果 'abc' 不可用,那么只有 props 值 'pqr' 应该添加到路径中。

 render() {
    if (this.props.abc?.status !== 'available') return null;
      console.info('Log value= ',this.props);

    const path = this.props.abc.value;
    
    return (
      <View
        getfile={path}   
       console.info('finished loading:', path); 
        }
      />
    );
  }

我想写一些类似的东西

render() {
        if (this.props.abc?.status !== 'available') return null;
        else if (this.props.pqr?.status !== 'available') return null;
          
          console.info('Log value= ',this.props);
          
        if (this.props.abc != null) {
        const path = this.props.abc.value;
        }
        else if (this.props.pqr != null) {
        const path = this.props.pqr.value;
        }
/* I know the above if -else if statement will fail as props value for 'abc' might not be null yet not have the required value in which case it would never go to the else if statement. */
        
        return (
          <View
            getfile={path}   
           console.info('finished loading:', path); 
            }
          />
        );
      }

在这里,我想检查 props 值是否可用于 abc 或 pqr,然后它应该分配该值。如何更好地编码?

任何建议表示赞赏。

【问题讨论】:

  • 好吧,如果 props 不可用,它将进入第一个 if 并退出。所以它永远不会归结为不可用的支票
  • else if (this.props.abc?.status !== 'available')if 的条件相同。你的意思是写pqr而不是abc吗?
  • @epascarello 道具值来自小部件,因此我可以将值传递给 abc 或 pqr。所以条件提到如果 abc 的道具值状态不可用,它应该检查 pqr 的道具值
  • 你的if的问题是,不设置的时候会退出。它不会继续下去。
  • @Barmar 是的,这是我现在编辑的错误。

标签: javascript react-native if-statement conditional-statements


【解决方案1】:

你可以把它简化成这样。

  • 使用解构从this.props 获取abcpqr 属性
  • 创建一个变量并将其分配给abc ?? pqr。如果abc 为空,则nested 将等于pqr
  • 如果nested?.status 返回未定义,!== 否定测试将为真。所以,检查nested?.status === 'available'。如果 nested 为 null 或 nested.status 不是“可用”,它将返回 false
const { abc, pqr } = this.props;

const nested = abc ?? pqr;

if (nested?.status === 'available') {
  const { path } = nested;
  return <View... >
}

return null

您可以进一步简化它。但是,我觉得它的可读性较差

const { abc, pqr } = this.props;
const { status, path } = abc ?? pqr ?? {};

if (status === 'available')
  return <View... >

return null

【讨论】:

  • 感谢@adiga 另一个问题是,我想设置 path = abc.value.uri(如果文件在 abc 中可用)或 path = pqr.value,所以我应该写一个 if-else 吗?
猜你喜欢
  • 2015-05-16
  • 2016-06-21
  • 2019-04-09
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多