gpt4 book ai didi

javascript - 我如何异步拦截点击

转载 作者:行者123 更新时间:2023-11-30 19:04:55 25 4
gpt4 key购买 nike

我有一个带有按钮的组件可以处理一些事情,我想将拦截器传递给该组件,这样我就可以在拦截器内调用 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,但是我如何返回一个只返回 truefalse 的 promise?
顺便说一句,我希望在拦截器完成之前禁用按钮

最佳答案

你需要返回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 })
})
}

关于javascript - 我如何异步拦截点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59089916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com