【发布时间】: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