我有一个带有处理某些内容的按钮的组件,我想将拦截器传递给该组件,这样我就可以在拦截器内部调用API
并寻求许可,如果许可被授予,组件按钮的onClick被执行,如果不执行,那么就不正确
所以现在我很难弄清楚该怎么做,这是一个显示我想做什么的sudo代码:
//Inside componentA which is using componentB
onClickInterceptor = () => {
axios.post(//something)
.then(response => {
// do a few thing and finally you know if you should return true or not
})
.catch(error => {
//you know you don't have permission
})
return //This is my problem, i don't know what to return, i don't want to return the axios post, i want something like a new promise ?
}
//Inside componentB
onButtonClick = (event) => {
if (this.props.onClickInterceptor) {
this.setState({ disableButton: true })
this.props.onClickInterceptor()
.then(permissionState) => {
if (permissionState) {
this.runTheMainCode()
}
else {
//dont do anything
}
this.setState({ disableButton: false })
}
}
else
this.runTheMainCode()
}
this.runTheMainCode() {
//...
}
现在我不知道要在 onClickInterceptor
中返回什么,我知道我不想返回axios
,但是如何返回像这样只返回true
或false
的承诺?
顺便说一句,我希望在拦截器完成之前禁用按钮
答案 0 :(得分:1)
您需要返回axios promise并在componentB上处理
//Inside componentA which is using componentB
onClickInterceptor = () => {
return axios.post(//something)
.then(response => {
// you can return false or true here
return true
})
.catch(error => {
throw error
})
}
//Inside componentB
onButtonClick = (event) => {
this.props.onClickInterceptor.then(returnedBoolean=>{
// here will come what you returned
this.setState({ disableButton: returnedBoolean })
}).catch(err=>{
// the error hadnling ....
this.setState({ error: true })
})
}