【问题标题】:react-native axios resolve callback function not executedreact-native axios解决回调函数未执行
【发布时间】:2017-10-28 20:54:47
【问题描述】:

我想在用 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))
}

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

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
  })
}

我将如何解决第二个代码块的承诺?

【问题讨论】:

  • 你为什么叫 this.onLoginSuccess.'bind(this)' 为什么不叫 this.onLoginSuccess()??
  • 因为我将 onButtoPress() 方法传递给子组件,所以我需要将执行上下文绑定到当前执行上下文。如果我没记错的话
  • 你试过调用 this.onLoginSuccess() 吗?因为回调在相同的上下文中工作(意味着执行上下文 = 绑定上下文)
  • 或者如果有必要将 ''this'' 传递给 onLoginSuccess 然后在 onLoginSuccess(context){context..setState({.....});}
  • 实际上调用 this.onLoginSuccess() 有效!谢谢!

标签: javascript react-native promise xmlhttprequest axios


【解决方案1】:

在我的情况下,它工作正常

  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){
 }

【讨论】:

    【解决方案2】:

    您在第二个示例中尝试做的是您只是将函数绑定到此实例,而不是进行调用。而不是将函数绑定到函数内部的此实例是一种不好的做法。它将绑定函数触发的次数,而不是在执行一次的构造函数中执行此操作。然后将该函数作为回调传递给 axios 解析和拒绝(即 then 和 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
        })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      • 2020-12-23
      • 2023-04-10
      相关资源
      最近更新 更多