Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React使用setState时未定义此选项_Javascript_Reactjs_This - Fatal编程技术网

Javascript React使用setState时未定义此选项

Javascript React使用setState时未定义此选项,javascript,reactjs,this,Javascript,Reactjs,This,嘿,伙计们,当使用setState时,尝试做出反应并遇到问题,我一直无法读取未定义错误的属性setState,我不确定如何修复它。我已经尝试在构造函数中使用bind,但仍然无法解决这个问题 谢谢你的意见 import React from 'react'; class Products extends React.Component { constructor(props) { super(props) this.state = {products:{}} this.getItems

嘿,伙计们,当使用
setState
时,尝试做出反应并遇到问题,我一直无法读取未定义错误的属性
setState
,我不确定如何修复它。我已经尝试在构造函数中使用bind,但仍然无法解决这个问题

谢谢你的意见

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;
从“React”导入React;
类产品扩展了React.Component{
建造师(道具){
超级(道具)
this.state={products:{}
this.getItems=this.getItems.bind(this)
}
componentDidMount(){
这个.getItems('http://lcboapi.com/products/300681,然后(函数(响应){
控制台日志(响应);
this.setState({products:response});
},函数(错误){
console.log('failed',error);
});
}
组件willmount(){
}
getItems(url){
返回新承诺(功能(解决、拒绝){
var req=新的XMLHttpRequest();
请求打开('GET',url);
请求setRequestHeader('授权','令牌');
req.onload=函数(){
如果(请求状态==200){
解决(请求响应);
}否则{
拒绝(错误(请求状态文本));
}
};
req.onerror=函数(){
拒绝(错误(“错误”));
};
请求发送();
});
}
render(){
返回(
你好
);
}
}
出口默认产品;

为了使
引用您可以
的组件。绑定(此)
函数

function(response) {
  console.log(response);
  this.setState({products:response});
}.bind(this)
如果您可以使用ES6,那么您也可以使用箭头功能,其中
自动绑定此

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

哇,整个晚上我都搞错了。箭头函数将此上下文向前推进,我不知道这一点。我们将进一步深入ES6!谢谢