14. 解构赋值
1. 对象的基本解构
- // 例子 14-1
-
- componentWillReceiveProps(newProps) {
- this.setState({
- active: newProps.active
- })
- }
-
- componentWillReceiveProps({active}) {
- this.setState({active})
- }
- // 例子 14-2
-
- // bad
- handleEvent = () => {
- this.setState({
- data: this.state.data.set("key", "value")
- })
- };
-
- // good
- handleEvent = () => {
- this.setState(({data}) => ({
- data: data.set("key", "value")
- }))
- };
- // 例子 14-3
-
- Promise.all([Promise.resolve(1), Promise.resolve(2)])
- .then(([x, y]) => {
- console.log(x, y);
- });
2. 对象深度解构
- // 例子 14-4
-
- // bad
- function test(fruit) {
- if (fruit && fruit.name) {
- console.log (fruit.name);
- } else {
- console.log('unknown');
- }
- }
-
- // good
- function test({name} = {}) {
- console.log (name || 'unknown');
- }
- // 例子 14-5
-
- let obj = {
- a: {
- b: {
- c: 1
- }
- }
- };
-
- const {a: {b: {c = ''} = ''} = ''} = obj;
3. 数组解构
- // 例子 14-6
-
- // bad
- const splitLocale = locale.split("-");
- const language = splitLocale[0];
- const country = splitLocale[1];
-
- // good
- const [language, country] = locale.split('-');
4. 变量重命名
- // 例子 14-8
-
- let { foo: baz } = { foo: 'aaa', bar: 'bbb' };
- console.log(baz); // "aaa"
5. 仅获取部分属性
- // 例子 14-9
-
- function test(input) {
- return [left, right, top, bottom];
- }
- const [left, __, top] = test(input);
-
- function test(input) {
- return { left, right, top, bottom };
- }
- const { left, right } = test(input);