reactjs - 如何修复 typeError:无法读取未定义的属性“地图”
问题描述
我想从 Json Server 获取数据,我需要在哪里编辑?
这是我得到的错误
“TypeError:无法读取未定义的属性‘地图’”
getPosts() {
axios.get("http://localhost:8001/employees")
.then(response => {
this.setState({
posts : response.data.posts,
isLoading: false
});
})
.catch(error => this.setState({error, isLoading : false}));
}
componentDidMount () {
this.getPosts();
}
render() {
const {isLoading , posts} = this.state;
return (
<React.Fragment>
<h2>Data JSON</h2>
<div>
{!isLoading ? (
posts.map(post => {
const {id, first_name, last_name, email} = post;
return (
<div>
<h2>{id}</h2>
<h2>{first_name}</h2>
<p>{last_name}</p>
<p>{email}</p>
<hr />
</div>
);
})
) : (
<p>Loading...</p>
)}
</div>
</React.Fragment>
);
}
}
导出默认登录;
我希望出现来自 json 服务器的数据,但不是
解决方案
将帖子的默认状态设置为数组,并将 if 语句添加到您的渲染函数以检查该组件是否应该渲染帖子。
class YourClassName extends React.Component {
state = {
posts: [],
}
getPosts() {
axios.get("http://localhost:8001/employees")
.then(response => {
this.setState({
posts : Array.isArray(response.data) ? response.data : response.data.posts,
isLoading: false
});
})
.catch(error => this.setState({error, isLoading : false}));
}
componentDidMount () {
this.getPosts();
}
render() {
<>
{posts.length > 0 && posts.map(post => <p>{post}</p>)}
</>
}
}
推荐阅读
- google-cloud-platform - 数天无法访问笔记本实例
- python - 使用包含特定键/值对的多个字典在 pyspark 数据帧上执行 regex_replace 而无需循环
- c++ - 使用有状态分配器持续清除、填充和交换 2 个容器
- r - 总是选择列表中的第一个元素
- micronaut - 未加载 Micronaut GCP 机密
- android - 如何在 JetpackCompose String 中访问复数资源
- java - 转换多值映射
到地图 >.object 是List的形式 - visualization - 可视化同素异形体本体套件
- javascript - 我已经在我的 Laravel 公共文件夹中上传了一个从 justinmind 原型生成的 html 模板
- android - 获取 TextView 的属性时忽略边距顶部