jor*_*dan 2 javascript this reactjs
嘿家伙尝试反应,并在使用时遇到问题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;
Run Code Online (Sandbox Code Playgroud)
为了使this参考组件,您可以使用.bind(this)该功能
function(response) {
console.log(response);
this.setState({products:response});
}.bind(this)
Run Code Online (Sandbox Code Playgroud)
如果您可以使用ES6,那么您也可以使用this自动绑定的箭头功能:
(response) => {
console.log(response);
this.setState({products:response});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1911 次 |
| 最近记录: |