简体   繁体   English

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

[英]Handling multiple axios get requests inside componentDidMount

I have a React component like this: 我有一个像这样的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
    }
 }`

As you can see I am making three API get requests to get the details and setting the state three times after getting the data. 如您所见,我正在发出三个API获取请求以获取详细信息,并在获取数据后三次设置状态。 Due to this, I am getting this error: 因此,我收到此错误:

Warning: Cannot update during an existing state transition (such as within render or another component's constructor). 警告:在现有状态转换期间(例如在render或其他组件的构造函数中)无法更新。 Render methods should be a pure function of props and state; 渲染方法应该纯粹是道具和状态的函数; constructor side-effects are an anti-pattern, but can be moved to componentWillMount . 构造函数的副作用是反模式,但是可以将其移至componentWillMount

By the way, I am not causing a state change in the render method. 顺便说一句,我没有在render方法中引起状态改变。 Anyway to solve this issue? 无论如何要解决这个问题?

As axios.get returns a promise, you can link them together before calling setState. 由于axios.get返回一个axios.get ,您可以在调用setState之前将它们链接在一起。 For example using Promise.all : 例如,使用Promise.all

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

Just beware that if any of the api calls fail, Promise.all will catch, and setState won't be called. 请注意,如果任何api调用失败,Promise.all将捕获,并且不会调用setState。

In axios you have the method axios.all : 在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
  }));

Or you can use the standard Promise.all : 或者,您可以使用标准的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