我正在尝试实现简单的承诺就是反应。
下面是我的代码:
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
};
}
componentWillMount() {
var promise = new Promise( (resolve, reject) => {
let name = 'Shubham'
if (name === 'Shubham') {
resolve("Promise resolved successfully");
}
else {
reject(Error("Promise rejected"));
}
});
promise.then( result => {
this.setState({name: result});
}, function(error) {
this.setState({name: error});
});
}
render() {
return (
<div className="App">
<h1>Hello World</h1>
<h2>{this.state.name}</h2>
</div>
);
}
}
export default App;
只要名称匹配,此方法就起作用。如果我将let name = 'Shubham'
更改为let name = 'Shaurya'
,则会出现错误Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined
。我不明白我在做什么错误。
答案 0 :(得分:1)
在您的Promise错误处理程序中,this
是指function
实例,而不是类组件的实例。将其更改为箭头功能:
promise.then( result => {
...
}, (error) => {
this.setState({name: error});
})