繁体   English   中英

在componentDidMount内部处理多个axios获取请求

[英]Handling multiple axios get requests inside componentDidMount

我有一个像这样的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或其他组件的构造函数中)无法更新。 渲染方法应该纯粹是道具和状态的函数; 构造函数的副作用是反模式,但是可以将其移至componentWillMount

顺便说一句,我没有在render方法中引起状态改变。 无论如何要解决这个问题?

由于axios.get返回一个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。

在axios中,您可以使用axios.all方法:

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));

或者,您可以使用标准的Promise.all

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

Promise.all([getUserAccount(), getUserPermissions()])
  .then(data => {
    // Both requests are now complete
  });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM