javascript - 在 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
.
顺便说一句,我不会在渲染方法中引起状态变化。无论如何要解决这个问题?
解决方案
作为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。
推荐阅读
- openthread - EFR32MG12 的 OpenThread 示例不会像在其 github 存储库中那样直接工作
- c# - 从一个项目异步发送单个数据到另一个项目
- java - 在 IntelliJ IDEA 中初始化 SpringBoot 2 应用程序时出现 NoClassDefFoundError
- python - add_argument() 的自定义操作 - bool 和 string 类型
- python - Django模板中的Wtform FieldList渲染
- apache-kafka-streams - Kafka 流在异常时停止线程
- swift - UIStackView 显示/隐藏动画
- youtube - 4 小时浏览观看、证书性能和多应用测试
- python - pytest 无法使用 __init__.py 加载测试模块
- jenkins - I t_RegisterApplication(),未能建立到 WindowServer 的默认连接,_CGSDefaultConnection() 为 NULL