首页 > 解决方案 > 在 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() 生命周期内,因此仅在安装组件时才执行?

提前致谢

标签: ajaxreactjs

解决方案


您可以使用isMounted()它来检查它是否已安装

if (this.isMounted()) {
  this.setState({...});
}

虽然这是一种反模式,但您可以在此处找到一些关于最佳实践解决方案的建议:https ://reactjs.org/blog/2015/12/16/ismounted-antipattern.html


推荐阅读