我有一个像这样的 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 tocomponentWillMount
.
顺便说一句,我没有在渲染方法中引起状态变化。无论如何要解决这个问题?
最佳答案
由于 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/