首页 > 解决方案 > 在 componentDidMount 中处理多个 axios get 请求

问题描述

我有一个这样的 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
    }
 }`

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

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

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

标签: javascriptreactjs

解决方案


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

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

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


推荐阅读