[英]ES6 object namespacing
我遇到了一些我以前沒見過的語法。 當我處理對象和使用React時,你可以通過這樣做來簡化命名空間
let {someProp} = prevProps
這樣做可以讓我每次想要使用時都避免編寫prevProps.someProp
。
我不明白的是這種語法
let {someProp: oldData} = prevProps
console.log(someProp)
將顯示的值prevPros.someProp
但哪里 oldData
從來???
此行上方的console.log(olddata)
將顯示undefined
但下面的console.log(oldData)
將顯示以前的props。
let {someProp: myAlias} = prevProps
此語法允許您使用別名,例如您可以在代碼中使用myAlias
,而不是someProp
,它被稱為Object destructuring
正如@FelixKling的評論所述, 這里是官方參考 。
提供的鏈接示例:
let o = {p: 42, q: true};
let {p: foo, q: bar} = o;
console.log(foo); // 42
console.log(bar); // true
是:
let {someProp} = prevProps
類似於:
let someProp = prevProps.someProp;
還有這個:
let {someProp: oldData} = prevProps
會是這樣的:
let oldData = prevProps.someProp
看看這個鏈接
基本上你是在解構 prevProps,在這種情況下, oldData
現在將具有someProp
的值
這種語法是ES6中稱為對象解構的閃亮新東西之一。
這是一個關於如何以不同方式使用解構的詳細示例
const person = {
first: 'Jack',
last: 'Daniels',
address: {
city: 'Dallas',
}
};
// destructure as it is
const { first, last } = person;
// destructure with custom name
const { first: firstName, last: lastName } = person;
// destructure with default value
const { first, last, middle = 'The Boss' } = person;
// destructure with custom name and default value
const { first, last, middle: middleName = 'The Boss' } = person;
// destructure nested keys
const { first, last, address: { city } } = person;
// destructure nested keys with custom name
const { first, last, address: { city: myCity } } = person;
// destructure nested keys safely
const { first, last, address: { city } = {} } = person;
// destructure rest of the values
const { first, ...rest } = person; // => rest will have all keys but first
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.