我希望在类中使用承诺,并依赖于是否解析或拒绝我的组件的类的另一个方法。这里我留下了一个代码。
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)
请使用.catch()
:
componentDidMount() {
let obj = {newName: ''};
promise.then(result => {
this.Bien(result)
})
.catch((error) => {
this.Mal(error)
});
}
所以总代码应该如下:
import React, { Component } from 'react';
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)
})
.catch(error => {
this.Mal(error)
});
}
render() {
return <></>
}
}
export default App;
在"react" 16.12.0"上工作正常。结果提示"fallo">