javascript - 在 componentDidMount 中处理多个 axios get 请求

标签 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
    }
 }`

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

Warning: Cannot update during an existing state transition (such as within render or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to componentWillMount.

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

最佳答案

由于 axios.get 返回一个 promise ,您可以在调用 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。

关于javascript - 在 componentDidMount 中处理多个 axios get 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53964846/

相关文章:

javascript - 如何在 DataTable 中显示加载/处理消息?

javascript - 检测点击标题图标

javascript - 如果选中两个单选按钮之一,则标记为 true

reactjs - 希望使用 react 钩子(Hook)传递所有 Prop

javascript - 添加 anchor 以 react 引导表

javascript - 存在的函数被列为 "undefined"

javascript - 将 Rails DB as_json.to_json 嵌入到 Javascript 中不起作用。 (变成“东西”)

javascript - 这是 shouldComponentUpdate 的合理实现吗?

android - 如何使 Modal 在 react-native 中显示为不同的组件

javascript - JSON - 未捕获类型错误 : Cannot read property of undefined