ajax - 在 componentDidMount 内的 API 调用之后的 setState
问题描述
我正在尝试实现一个自定义选择,它显示从 API 获取的语言列表。
我在 componentDidMount 生命周期挂钩中进行 api 调用,然后根据获取的数据更新组件的状态。
一切似乎都正常,但我总是收到这个错误:
警告:setState(...):只能更新已安装或正在安装的组件。这通常意味着您在未安装的组件上调用了 setState()。这是一个无操作。请检查 LanguageSelect 组件的代码。
这是我的代码片段:
export default class LanguageSelect extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: false,
languages: []
};
}
// ...
componentDidMount() {
http.get('/api/parameters/languages')
.then(
// the Array.map is just to restructure the data fetched form the API
data => this.setState({ languages : data.map(l => ({ label: l.LocalName, value: l.Code, })) }),
// Error case
error => console.error('Error: Languages data could not be fetched', error)
)
}
// Render function
}
我不明白,我所做的唯一 setState 调用是在 componentDidMount() 生命周期内,因此仅在安装组件时才执行?
提前致谢
解决方案
您可以使用isMounted()
它来检查它是否已安装
if (this.isMounted()) {
this.setState({...});
}
虽然这是一种反模式,但您可以在此处找到一些关于最佳实践解决方案的建议:https ://reactjs.org/blog/2015/12/16/ismounted-antipattern.html
推荐阅读
- java - 如何在方法参数中验证 Spring Rest 控制器中的 protobuf 消息
- python-3.x - 使用有序字典中的参数从正态分布中采样
- java - 具有多个调度程序 servlet 的 InternalResourceViewResolver
- jhipster - Jhipster Heroku 部署错误
- ios - 侧边菜单如何覆盖状态栏的一部分
- java - 如何为 Spring 项目找到正确的工件 ID
- jquery - 如何在jquery分页插件中使用图像
- bash - Bash 检查云代工日志
- dart - 在 Android 和 iOS 中为图像颤振单独的文件夹
- c++ - 如何将 c++ 编译器添加到 docker 容器中?