2016-08-23 54 views
2

我的代碼有什麼問題? 我有一個錯誤,當我從API獲取JSON:reactjs setState不是JSON調用的函數

this.setState不是一個函數

代碼:

class App extends React.Component { 

    constructor(props) { 
     super(props); 

     this.state = { 
     data: [] 
     } 
    }; 

    componentWillMount() { 

     const url = 'myurl'; 

     http.get(url, function(res){ 
     var body = ''; 

     res.on('data', function(chunk){ 

      body += chunk; 

     }); 

     res.on('end', function(){ 

      var res = JSON.parse(body); 
      console.log(res); 
      this.setState({data: res}); 

     }.bind(this)); 

     }).on('error', function(e){ 
      console.log("Got an error: ", e); 
     }); 
    } 
} 
+0

提示#1:'的console.log(本);' – zerkms

回答

1

你被bind做正確的事情荷蘭國際集團但是,您需要爲外部http.get方法執行相同的操作:

http.get(url, function(res){ 
var body = ''; 

res.on('data', function(chunk){ 

    body += chunk; 

}); 

res.on('end', function(){ 

    var res = JSON.parse(body); 
    console.log(res); 
    this.setState({data: res}); 

}.bind(this)); 

}.bind(this)) 
+0

非常感謝您 – gig

+0

不用擔心,祝你好運 – Chris

1

你也可以用這種方式

class App extends React.Component { 

constructor(props) { 
    super(props); 

    this.state = { 
     data: [] 
    } 
}; 

componentWillMount() { 
    var self = this; 
    const url = 'myurl'; 

    http.get(url, function (res) { 
     var body = ''; 
     res.on('data', function (chunk) { 
      body += chunk; 
     }); 

     res.on('end', function() { 
      var res = JSON.parse(body); 
      console.log(res); 
      self.setState({ data: res }); 

     }) 

    }).on('error', function (e) { 
     console.log("Got an error: ", e); 
    }); 
}} 
相關問題