首页 > 解决方案 > Waiting for request to finish before performing operation ReactJS

问题描述

I have an axios call inside my react application

  }).then(res =>
       this.setState({
           name: res.data.fname,
           sName: res.data.sname,
           percentage: res.data.percentage,
           result: res.data.result,
           showResult: true,
           type: this.typeHandler(res.data.percentage)
       }));
       }

after the request is done AND the state is set, I want to set input forms to blank. So i tried this

  }).then(res =>
       this.setState({
           name: res.data.fname,
           sName: res.data.sname,
           percentage: res.data.percentage,
           result: res.data.result,
           showResult: true,
           type: this.typeHandler(res.data.percentage)
       })
       ).then(
       this.setState(prevState =>{
          return {inputName: '', inputSname: ''} 
       }))
       }

using another promise, being resolved after the first, but the forms are still set to blank before the request state is being set. I have tried using a callback as well, but the first .then() method, does not accept a second argument. How can I solve this?

标签: reactjs

解决方案


setState 可以得到回调

https://reactjs.org/docs/react-component.html#setstate

setState(updater[, callback])

而不是另一个然后将此回调传递给 setState


推荐阅读