2017-03-06 57 views
0

我知道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) 
     }) 

我想更新this對象,它是不是then函數內部訪問,因此,我已存儲this對象that功能之前的狀態,但我想申請在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) 
    }) 

箭頭函數將使用與父函數相同的作用域,對於這些情況非常方便。

還有一件事,我不建議多次撥打setState。當所有數據準備好使用時,您應該在回調結束時只調用一次。

+0

謝謝:) 適合我。 是的,會記住這一點 –