2017-03-06 6 views
0

thisオブジェクトは変更できませんが、別の方法が必要であるというルールを知っています。"this"オブジェクトをどのように変更するのですか

var that= this 
     axios.get('http://ec2-54-165-240-14.compute-1.amazonaws.com:3000/api/foodItem').then(function(data){ 
      console.log("inside axios ",data) 
      that.setState({ 
       items : data, 
      }); 
      var curGroupId = that.props.cartReducer.val; 
      var items = that.state.items ; 
      var curItems= []; 
      for(var i in items){ 
       if(items[i].food_group_id==curGroupId){ 
        curItems.push(items[i]); 
       } 
      } 
      that.setState({ 
       curItems : curItems 
      }) 

     }).catch(function(err){ 
      console.log(err) 
     }) 

私はthen関数内でアクセスすることはできませんので、私は関数の前にthatthisオブジェクトを格納しているが、私はthisオブジェクトの変更を適用するthisオブジェクトの状態を更新したいです。

答えて

2

矢印機能を使用すると、内側の機能の内側にthisにアクセスできます。

axios.get('http://ec2-54-165-240-14.compute-1.amazonaws.com:3000/api/foodItem') 
    .then((data) => { 
     console.log("inside axios ",data) 
     this.setState({ // <---- references to the parent scope 
      items : data, 
     }); 
     var curGroupId = that.props.cartReducer.val; 
     var items = that.state.items ; 
     var curItems= []; 
     for(var i in items){ 
      if(items[i].food_group_id==curGroupId){ 
       curItems.push(items[i]); 
      } 
     } 
     this.setState({ // this too ;) 
      curItems : curItems 
     }) 

    }).catch((err) => { 
     console.log(err) 
    }) 

矢印関数は親関数と同じスコープを使用します。これらの状況では非常に便利です。

もう1つは、setStateを複数回呼び出すことをおすすめしません。すべてのデータを使用できるようになると、コールバックの最後にコールする必要があります。

+0

ありがとう:) 私のために働く。 はい、それを念頭に置いておきます –

関連する問題