2017-01-11 32 views
1

所以在我的陣營項目,我有一個後備的默認狀態,看起來像這樣的地址形式:使用每個等於null的鍵實例化對象的最佳方法?

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?

+1

難道他們絕對需要明確設置爲'null'?不能使用這些屬性的任何代碼只接受'undefined'作爲一個空值,以便您可以:'newLocation:this.props.location || {}'。 – CodingIntrigue

回答

2

你可以使用一個數組和遍歷鍵,並建立一個新的對象與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可以被定義爲組件類本身的屬性,以設置類的默認的道具。這用於未定義的道具,但不適用於null道具。例如:

class CustomButton extends React.Component { 
    // ... 
} 

CustomButton.defaultProps = { 
    color: 'blue' 
}; 
+0

這並沒有真正回答這個問題。我的意思是,你仍然必須明確地將所有這些屬性設置爲空。 – CodingIntrigue

+0

然後,如果你想一個一個地設置它 –

相關問題