Rest/Spread Properties题造,目前是Stage 3的特性。
在使用Babel編譯后谍椅,表現(xiàn)出了順序相關(guān)性误堡,如果多個被展開的對象具有同名屬性,會產(chǎn)生沖突雏吭,后者覆蓋前者锁施。
1. 用于對象的屬性中
const a = { x: 1 };
const b = { x: 2 };
const r1 = {...a,...b };
const r2 = {...b,...a };
console.warn(JSON.stringify(r1)); //{"x":2}
console.warn(JSON.stringify(r2)); //{"x":1}
2. 用于React組件的屬性中
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
const a = { x: 1 };
const b = { x: 2 };
class A extends Component {
render() {
return (
<div>
<span {...a} {...b}>ab</span>{/* "x"=2 */}
<span {...b} {...a}>ba</span>{/* "x"=1 */}
</div>
);
}
}
ReactDOM.render(
<A />,
document.getElementById('page')
);
注:
(1)Rest/Spread Properties可用于獲取剩余屬性
const a = { x: 1, y: 3 };
const {x,...u} = a;
console.info(JSON.stringify(u)); //{"y":3}
(2)剩余屬性可以為空
const a = { x: 1 };
const {x,...u} = a;
console.info(JSON.stringify(u)); //{}
(3)不能同時出現(xiàn)兩個:Cannot have multiple rest elements when destructuring.
const a = { x: 1, y: 3 };
const {x,...u,...v} = a;