來自一個react SPA的總結--es6的應用

這篇主要總結一些,es6在react中的應用,並沒有囊括所有,只是總結一些本人平常沒有理解的知識點………..

1.ES6 Arrow Functions

es6的箭頭函數在這個簡單project中用到多次,下面以一個對比代碼塊展示一下:

// Old way with ES5
componentDidMount: function() {
  userApi.getList().then(function(users) {
    this.setState({users: users});
  });
},

// New way with ES6 Arrow Functions
componentDidMount: function() {
  userApi.getList().then(users => {
    this.setState({users: users});
  });
}

注意參數的地方,如果原先函數中沒有參數或者有多於一個參數,則不能省去()哦!使用箭頭函數,可以避免各種this指向的問題,下一篇文章會有介紹哦。點擊查看吧


2.ES6 Spread Operator

在這個project中,使用es6的解構賦值來給component傳遞參數,下面通過代碼段來展示這種用法:

假設我們想從parent component傳遞一個對象給child component:

// Parent Component's render method
render: function() {
  const user = {
    name: 'Brad',
    occupation: 'Web Development',
    state: 'Arizona'
  };

  return (<ChildComponent user={user} />);
}

通過這種user={user}的方式傳遞數據,如果子組件想要獲得name這個數據,就需要通過this.props.user.name的方式獲取數據,看下面這種方式

// Parent Component's render method
render: function() {
  const user = {
    name: 'Brad',
    occupation: 'Web Development',
    state: 'Arizona'
  };

  return (<ChildComponent name={user.name} occupation={user.occupation} state={user.state} />);
}

這種方式,子組件想要獲得name或全部數據,需要this.props.name,前提是要像這樣name={user.name} occupation={user.occupation} state={user.state}哦,也是挺麻煩的,所以使用es6的特性之一,解構賦值方便了許多哦!看下面的代碼塊:

// Parent Component's render method
render: function() {
  const user = {
    name: 'Brad',
    occupation: 'Web Development',
    state: 'Arizona'
  };

  return (<ChildComponent {...user} />);
}

這樣,子組件只需要this.props.name,this.props.occupation,this.props.state方式就能獲得傳遞過來的數據了

更詳細的請看react官方文檔Spread Attributes

發佈了30 篇原創文章 · 獲贊 2 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章