【发布时间】:2021-05-26 18:36:47
【问题描述】:
我希望在一个类中使用一个承诺,并取决于解决或拒绝是否执行我的组件类的另一个方法。 在这里我留下一个代码。
var promise = new Promise( (resolve, reject) => {
let name = 'DaveA'
if (name === 'Dave') {
resolve("Promise resolved successfully");
}
else {
reject(Error("Promise rejected"));
}
});
class App extends React.Component
{
constructor(props){
super(props);
this.state = {
name: '',
}
}
Bien(result){
alert("OK")
this.setState({name: result});
}
Mal(error){
alert("FALLO")
this.setState({name: error});
}
componentDidMount() {
let obj = {newName: ''};
promise.then( result => {
this.Bien(result)
}, function(error) {
this.Mal(error)
});
我创建了一个简单的承诺。 从 ComponentDidMount 我调用它。 在我调用另一种方法之后。 但从不调用它。 出现错误:
WARN Possible Unhandled Promise Rejection (id: 0):
TypeError: this.Mal is not a function. (In 'this.Mal(error)', 'this.Mal' is undefined)
【问题讨论】:
-
在构造函数中添加 this.Mal = this.Mal.bind(this)
-
删除 function(error) {...} 部分并在 promise.then() 的末尾添加 .catch()。请检查以下答案。
标签: javascript reactjs react-native promise callback