Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

javascript - 我如何异步拦截点击(How can i intercept an on-click asynchronously)

I have a component with a button which handles some stuff, i want to pass an interceptor to this component so i can call an API inside the interceptor and ask for permission, if permission is granted the code inside the component's button's onClick is executed and if not, well it is not(我有一个带有处理某些内容的按钮的组件,我想将一个拦截器传递给此组件,以便我可以在拦截器内部调用API并寻求许可,是否授予了许可,执行了组件按钮的onClick中的代码,以及不,不是)


So right now i'm having trouble figuring out what to do, here is a sudo code showing what i want to do:(所以现在我很难弄清楚该怎么做,这是一个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() { //... } Right now i don't know what to return inside onClickInterceptor , i know i don't want to to return the axios , but how can i return a promise like that which only returns true or false ?(现在我不知道在onClickInterceptor内部返回什么,我知道我不想返回axios ,但是我怎么能返回只返回truefalse的promise?)
By the way, i want the button to be disabled until the interceptor is done(顺便说一句,我要禁用按钮,直到拦截器完成)   ask by Ali Ahmadi translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to return the axios promise and handle it at the componentB(您需要返回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 }) }) }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...