在 componentDidMount 中处理多个 axios get 请求

use*_*829 1 javascript reactjs

我有一个这样的 React 组件:

class Example extends Component {
   constructor(props) {
     super(props);

     this.state = {
       name: '',
       address: '',
       phone: ''
     }
   }

   componentDidMount() {
     //APIcall1 to get name and set the state
     //i.e., axios.get().then(this.setState())
     //APIcall2 to get address and set the state
     //APIcall3 to get phone and set the state
    }
 }`
Run Code Online (Sandbox Code Playgroud)

如您所见,我发出了三个 API 获取请求以获取详细信息并在获取数据后设置状态三次。因此,我收到此错误:

警告:无法在现有状态转换期间更新(例如在render组件内部或其他组件的构造函数中)。Render 方法应该是 props 和 state 的纯函数;构造函数的副作用是一种反模式,但可以移至componentWillMount.

顺便说一下,我不会在渲染方法中引起状态变化。无论如何要解决这个问题?

Mat*_*Way 5

作为axios.get返回承诺,您可以在调用 setState 之前将它们链接在一起。例如使用Promise.all

componentDidMount() {
  Promise.all([
    APIcall1, // i.e. axios.get(something)
    APIcall2,
    APIcall3
  ]).then(([result1, result2, result3]) => {
    // call setState here
  })
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果任何 api 调用失败, Promise.all 将捕获,并且不会调用 setState。