Hey guys trying react out and having an issue when using setState
, I keep getting Cannot read property setState
of undefined error and I'm not sure how to fix it. I've tried using bind in the constructor but that still doesn't fix the issue.
Thanks for your input.
import React from 'react';
class Products extends React.Component {
constructor(props) {
super(props)
this.state = {products:{}}
this.getItems = this.getItems.bind(this)
}
ponentDidMount() {
this.getItems('').then(function(response){
console.log(response);
this.setState({products:response});
},function(error){
console.log('failed',error);
});
}
ponentWillMount() {
}
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;
Hey guys trying react out and having an issue when using setState
, I keep getting Cannot read property setState
of undefined error and I'm not sure how to fix it. I've tried using bind in the constructor but that still doesn't fix the issue.
Thanks for your input.
import React from 'react';
class Products extends React.Component {
constructor(props) {
super(props)
this.state = {products:{}}
this.getItems = this.getItems.bind(this)
}
ponentDidMount() {
this.getItems('http://lcboapi./products/300681').then(function(response){
console.log(response);
this.setState({products:response});
},function(error){
console.log('failed',error);
});
}
ponentWillMount() {
}
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;
Share
Improve this question
edited Feb 20, 2017 at 19:34
Barry Michael Doyle
10.7k33 gold badges98 silver badges159 bronze badges
asked Feb 20, 2017 at 19:24
jordanjordan
3492 gold badges7 silver badges19 bronze badges
1 Answer
Reset to default 7In order to make this
refer to the ponent you can .bind(this)
the function
function(response) {
console.log(response);
this.setState({products:response});
}.bind(this)
If you can use ES6 then you can also use an arrow function where this
is automatically bound:
(response) => {
console.log(response);
this.setState({products:response});
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745489733a4629934.html
评论列表(0条)