【问题标题】:react-native Destructuring props [duplicate]反应原生解构道具[重复]
【发布时间】:2022-01-22 14:32:55
【问题描述】:

为什么我在解构 props 时设置了默认值会得到 undefined 错误或 null 错误? 我在MDN上看到,做解构的时候可以设置默认值。 当值为null时,不能被引用,所以我把默认值作为一个空数组,但是不知道为什么会报错。引用属性为空时不应该设置默认值吗? 如果您能告诉我我做错了什么,我将不胜感激。

//This is the props dummy data value.
displayOptions = {
 isVisible: true,
 displayImages : null,
 setting:{...some data}
 ....
}
class DisplayScreen extends React.Component {
  render() {
    const {displayImages = []} = this.props.displayOptions ;  
     <React.Fragment>
            {!this.state.isShowMenu && displayImages.length > 0 && (
              <React.Fragment>
                <S3Image
                  imgKey={displayImages[0].key}
                  level={displayImages[0].level}
                />
                ....
              </React.Fragment>
            )}
           ......
     </React.Fragment>


  }
}

【问题讨论】:

  • 尝试验证this.props实际上包含displayOptions
  • 检查了 this.props 有一个 displayOptions 你还有其他理由猜测吗?
  • 您看到的确切错误是什么?你能发布控制台输出吗?

标签: react-native


【解决方案1】:

错误可能是由于 displayImages 没有属性长度,因为它的值为 null。只有 undefined 会采用默认值。如下所示

displayOptions = {
 isVisible: true,
 displayImages : undefined,
 setting:{...some data}
 ....
}

reference 来自重复问题destructuring assignment default value

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-27
    • 2017-12-01
    • 2018-12-15
    • 1970-01-01
    • 2019-01-22
    • 2021-10-27
    • 1970-01-01
    • 2021-07-05
    相关资源
    最近更新 更多