首页 > 解决方案 > TypeError:this.state.annonces.map 不是函数

问题描述

嗨,我有一个 API,从代表我的前端的 React 我从 API 恢复数据以显示它,但从那里我遇到了这个问题。

预先感谢您指导我,向我解释清楚问题所在

    constructor(props) {
  super(props);
  this.state = {

    api: api.api,
    annonces: []
  }

}

componentDidMount = () => {
  console.log(this.state.annonces_id)
  this.onLoaodPreloader();
  this.getAnnonce();
}
getAnnonce = () => {
  var baseApiUrl = this.state.api
  axios.get(baseApiUrl + 'annonces' ,
    {
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${localStorage.usertoken}`
      }
    }).then((response) => {
      console.log(response)
      this.setState({
        annonces: response.data,
      })

    }).catch((erreur) => {
      console.log(erreur)
    })
}
render() {
        console.log(this);
            const { annonces } = this.state
        const renderAnnonces = annonces.map((annonces, index) =>{
              return (
                  <div className="col-md-6 col-sm-6 mb-3" key={index}>
                    {annonces.meeting_type}
                    </div>
              )

        });

  return <div className="component-annonces">{renderAnnonces}</div>;
}

标签: javascriptreactjs

解决方案


很确定你response.data不是一个数组。因为.map只有当它是一个数组时才有效。

如果你console.log('response data type :', typeof response.data)会看到数据是什么类型。

您的数据需要在一个数组中.map才能工作


推荐阅读