Skip to content

Latest commit

 

History

History
92 lines (84 loc) · 1.51 KB

6.jses6.md

File metadata and controls

92 lines (84 loc) · 1.51 KB

JavaScript ES6 in React

  • let 等於更嚴謹的 var 變數宣告

    • var 宣告後能在任何地方調用,let 只能在自己的區塊有效
    {
      let a = 10;
      var b = 1;
    }
    
    a // ReferenceError: a is not defined.
    b // 1
    
    • let 不允許重複宣告
    let abc = '456';
    let abc = '456';
    // Identifier 'abc' has already been declared
    
  • const 宣告後不能改變

  • 解構賦值 範例

    let a = [1,2,3];
    let b = [4,5,6];
    console.log([...a, ...b]);
    // 輸出 [1, 2, 3, 4, 5, 6]
    

    React 常用範例 1:

    let newItem = "新資料";
    this.setState({
      data: [...this.state.list, newItem],
    });
    
    // 這樣不會更新因為
    this.setState({
      data: this.state.list.push(newItem),
    });
    

    React 常用範例 2: 從 state、props 拿值

    let { list } = this.state;
    const { title } = this.props;
    
  • 箭頭函數 範例 1:

    let f = v => v;
    

    等同於

    let f = function(v) {
      return v;
    }
    

    範例 2:

    let f = () => 5;
    

    等同於

    var f = function () { return 5 };
    
  • 三元運算子

    import React, { Component } from 'react';
    import { Text, View } from 'react-native';
    
    class Sample extends Component {
      constructor(props) {
        super(props);
        this.state = {
          show: true,
        }
      }
      render() {
        return (
          <View>
            {
              this.state.show ? <Text>顯示文字</Text> : null
            }
          </View>
        );
      }
    }