react-native axios 解析回调函数未执行

react-native axios resolve callback function not executed

我想在使用 axios 发出 post 请求后设置回调函数。 此代码有效。

onButtonPress(){
this.setState({ status: null, loading: true });

axios.post(url, {
    'email': this.state.email,
    'password': this.state.password
})
.then(response => {
  this.setState({
    email: '',
    password: '',
    status: 'Authentication Successful',
    loading: false
  })
})
.catch(this.onLoginFail.bind(this))
}

但是当像这样将回调分配给一个单独的函数时,该函数不会解析 promise

onButtonPress(){
this.setState({ status: null, loading: true });

axios.post(url, {
    'email': this.state.email,
    'password': this.state.password
})
.then(response => {
  this.onLoginSuccess.bind(this)
})
.catch(this.onLoginFail.bind(this))
}

onLoginSuccess(){
  this.setState({
    email: '',
    password: '',
    status: 'Authentication Successful',
    loading: false
  })
}

我将如何像第二个代码块一样解决承诺?

你在第二个例子中试图做的是你只是将函数绑定到这个实例,而不是进行调用。而不是将函数绑定到函数内部的此实例是一种不好的做法。它将绑定函数触发的次数,而不是在执行一次的构造函数中执行此操作。然后将函数传递给axios resolve and reject(也就是then and catch)作为回调。

constructor(props) {
    super(props);
    this.onLoginSuccess=this.onLoginSuccess.bind(this);
    this.onLoginFail=this.onLoginFail.bind(this);
    this.onButtonPress=this.onButtonPress.bind(this);
} 

onButtonPress(){
     this.setState({ status: null, loading: true }, ()=> {
         axios.post(url, {
             'email': this.state.email,
             'password': this.state.password
         })
         .then(this.onLoginSuccess)
         .catch(this.onLoginFail);
     });
}

onLoginSuccess(){
    this.setState({
        email: '',
        password: '',
        status: 'Authentication Successful',
        loading: false
    })
}

就我而言,它工作正常

  axios.post(Urls.UploadImage, bodyFormData, {
    headers: {
      "Content-Type": "multipart/form-data",
      Authorization: "Bearer Token" 
    }
  })
  .then((response) => this.onUploadSuccess(response))
  .catch((error) => this.onUploadError(error));


 onUploadSuccess(response){
 }

 onUploadError(error){
 }