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

问题描述

我正在尝试使用 fetch 从 mongodb 数据库中获取数据到我的 reactjs 前端,但我不断收到上述错误。我也尝试过使用 axios 并不断收到相同的错误。可能是什么问题?任何帮助,将不胜感激。

import React, { Component } from 'react';
export default class App extends Component {

constructor() {
    super();
    this.state = { 
      propertydetails: []
     };
}

componentDidMount() {
    fetch('http://localhost:5000/property')
    .then(res => res.json())
    .then(propertydetails => this.setState({ propertydetails }, () => console.log('Data fetched', propertydetails)).catch(error => {
      console.log(error)
    }));

}
render() {
    return (

      <ul>
        {this.state.propertydetails.map(propertydetail => 
          <li key={propertydetail.id}>{ propertydetail.apartmentName}</li>
          )}
      </ul>
        
    )
}
}

标签: node.jsreactjsfetch

解决方案


您确定 API 返回一个数组吗?您还可以添加保护条件。如果您可以尝试控制台记录 api 响应并检查 API 是否返回数组或对象,那就太好了。

import React, { Component } from 'react';
export default class App extends Component {

constructor() {
    super();
    this.state = { 
      propertydetails: []
     };
}

componentDidMount() {
    fetch('http://localhost:5000/property')
    .then(res => res.json())
    .then(propertydetails => {
         console.log('propertydetails',propertydetails)
         this.setState({propertydetails});
    })
    .catch(e=>console.log('error', e);

}
render() {
    return (
      <ul>
        {this.state.propertydetails && this.state.propertydetails.map(propertydetail => 
          <li key={propertydetail.id}>{ propertydetail.apartmentName}</li>
          )}
      </ul>
        
    )
}
}

推荐阅读