node.js - 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>
)
}
}
解决方案
您确定 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>
)
}
}
推荐阅读
- javascript - 如何一次在“显示:flex”上只有 1 个 div
- javascript - 为什么背景图像中的图像是强奸?
- excel - 我需要帮助找到一个公式来格式化我的 Excel 数据库
- javascript - 如何使用 Leaflet.js 动态生成地图?
- objective-c - How to add uncompiled .mlmodel to Xcode UnitTests bundle
- maven - Jackson XML parsing MismatchedInputException
- python - 数据库内容未在 Django 中显示
- c# - ASP. Net Core integration tests
- python - 更改订阅日历中事件颜色时的 403 禁止响应
- java - 尝试在空对象引用上调用 Playerview.setplayer 上的虚拟方法