2017-02-20 65 views
2

嘿家伙试图反应出来,有一个问题,当使用setState,我一直得到无法读取属性setState未定义的错误,我不知道如何解决它。我试过在构造函数中使用绑定,但仍不能解决问题。反应这是不明确的,当使用setState

感谢您的输入。

import React from 'react'; 

class Products extends React.Component { 
constructor(props) { 
super(props) 
this.state = {products:{}} 
this.getItems = this.getItems.bind(this) 
} 

componentDidMount() { 
    this.getItems('http://lcboapi.com/products/300681').then(function(response){ 
    console.log(response); 
    this.setState({products:response}); 
},function(error){ 
    console.log('failed',error); 
}); 
} 
componentWillMount() { 

} 

getItems(url){ 

return new Promise(function (resolve,reject) { 
    var req = new XMLHttpRequest(); 
    req.open('GET',url); 
    req.setRequestHeader('Authorization','Token Token'); 


    req.onload = function(){ 
    if(req.status == 200){ 
     resolve(req.response); 
    }else{ 
     reject(Error(req.statusText)); 
    } 
    }; 

    req.onerror = function(){ 
    reject(Error("Error")); 
    }; 

    req.send(); 

}); 

} 

render() { 
return (
<div> 
    hi 
</div> 
); 
} 
} 
export default Products; 

回答

7

为了使this指组件,您可以.bind(this)功能

function(response) { 
    console.log(response); 
    this.setState({products:response}); 
}.bind(this) 

如果你可以使用ES6那么你也可以使用箭头函数,其中this自动绑定:

(response) => { 
    console.log(response); 
    this.setState({products:response}); 
} 
+0

打我冲,upvote ;-) – lustoykov

+0

哇,我整个晚上都错了。箭头功能将这种背景向前推进,我不知道这一点。将多一点潜入ES6!谢谢! –