javascript - 访问 prop 属性时处理 null prop 的最佳实践

标签 javascript reactjs

我有一个 React 组件,我传递了一个 Prop ,我用它来设置组件的初始状态:

class ContactForm extends React.Component {
  constructor(props) {
    super(props)

    const { contact } = this.props
    const { name, position, email, phone_number } = contact

    this.state = {
      name: name,
      position: position,
      email: email,
      phone_number: phone_number
    }
  }
}

但是,我传递的 contact 属性可能为空。当我尝试访问 prop 属性时,处理 null prop 的最佳方法是什么?我可以有一个 if 语句来检查 contact 是否为 null,并将状态设置为 null,如下所示:

if (contact) {
  const { name, position, email, phone_number } = contact

  this.state = {
    name: name,
    position: position,
    email: email,
    phone_number: phone_number
  }
} else {
  this.state = {
    name: '',
    position: '',
    email: '',
    phone_number: ''
  }
}

但我想知道是否有更好的方法

最佳答案

您可以将 contact 默认为空对象,并将其他值默认为空字符串:

class ContactForm extends React.Component {
  constructor(props) {
    super(props)
    // Only undefined values can be given default values when destructuring,
    // so it needs to be written like this
    const contact = this.props.contact || {}
    const { name = '', position = '', email = '', phone_number = '' } = contact

    this.state = {
      name,
      position,
      email,
      phone_number
    }
  }
}

关于javascript - 访问 prop 属性时处理 null prop 的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51011971/

相关文章:

javascript - JS : How to change the value of an object's property according to that object attribute

reactjs - 如何检查坐标是否包含在 map 的当前视口(viewport)中?

javascript - 根据子组件的输入过滤数据

javascript - 理解 React 中 array.map() 范围的问题

css - 在 React 应用程序中刷新页面后删除一个类

javascript - 在创建时动态动画元素

javascript - 识别 JavaScript 对象或关联数组中的最后一项

javascript - 在 jQuery Radio 选项状态更改中使用 every() 的问题

javascript - 具有自定义 x 轴和条宽的 d3 条形图

reactjs - 使用react-css-module和postcss-nested后,vscode无法识别css嵌套语法