【问题标题】:Best way to instantiate an object with every key equal to null?用每个键都等于 null 来实例化对象的最佳方法?
【发布时间】:2017-05-26 04:10:52
【问题描述】:

所以在我的 React 项目中,我有一个地址表单的后备默认状态,如下所示:

state = {
  newLocation: this.props.location || {
    lat: null,
    lng: null,
    street: null,
    complement: null,
    neighbourhood: null,
    city: null,
    state: null,
    zipCode: null,
    country: null,
  },
}

然而,将这么大的对象定义为所有键都为空,这感觉相当荒谬。有没有更短的方法来做到这一点? ES6/ES7 中有什么?

【问题讨论】:

  • 它们是否绝对需要明确设置为null?任何使用这些属性的代码都不能只接受undefined 作为一个空值,这样你就可以拥有:newLocation: this.props.location || {}

标签: javascript object ecmascript-6 ecmascript-2016


【解决方案1】:

您可以使用数组并迭代键并使用Object.assign 构建一个新对象。

var keys = ['lat', 'lng', 'street', 'complement', 'neighbourhood', 'city', 'state', 'zipCode', 'country'],
    loc = { lat: 123, lng: 246, city: 'NY', country: 'USA' },
    state = {
        newLocation: Object.assign(keys.reduce((o, k) => Object.assign(o, { [k]: null }), {}), loc)
    };

console.log(state);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

    【解决方案2】:

    使用 defaultProps 方法

    defaultProps 可以定义为组件类本身的属性,用于设置类的默认道具。这用于未定义的道具,但不适用于空道具。例如:

    class CustomButton extends React.Component {
      // ...
    }
    
    CustomButton.defaultProps = {
      color: 'blue'
    };
    

    【讨论】:

    • 这并不能真正回答问题。我的意思是,无论如何,您仍然必须将所有这些属性显式设置为 null。
    • 如果你想一个一个地设置它就让它不定义
    猜你喜欢
    • 2010-09-29
    • 1970-01-01
    • 2015-09-23
    • 1970-01-01
    • 2017-04-07
    • 2016-01-25
    • 2014-01-17
    • 1970-01-01
    • 2012-08-17
    相关资源
    最近更新 更多