javascript - TypeError:无法在 React 中读取未定义的属性(读取 'id')
问题描述
我已经建立了一个网站,但是在 3 次后按“加载更多”按钮时遇到问题。它给了我一个错误“TypeError:无法读取未定义的属性(读取'id')”......我猜切片和映射函数有问题!PS我试图将“id”调用到其他组件但徒劳无功!
class PostsList extends React.Component {
constructor(props) {
super(props);
this.state = {
posts: [],
visible: 3,
error: false
};
this.loadMore = this.loadMore.bind(this);
}
loadMore() {
this.setState((prev) => {
return {visible: prev.visible + 3};
});
}
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/posts").then(
res => res.json()
).then(res => {
this.setState({
posts: res
});
}).catch(error => {
console.error(error);
this.setState({
error: true
});
});
}
render() {
const { classes } = this.props;
return (
<div className={classes.section}>
<h2 className={classes.title}>Latest news</h2>
<div>
<GridContainer>
{
this.state.posts.slice(0, this.state.visible).map((post, i) => {
return (
<PostCard key={i}
id={posts[i].id}
date={posts[i].date}
fbimg={posts[i].fbimg}
description={posts[i].description}
fbpost={posts[i].fbpost}
/>
);
})
}
</GridContainer>
<GridContainer>
<GridItem>
{this.state.visible < this.state.posts.length &&
<Button
color="info"
onClick={this.loadMore}
>
Load more
</Button>
}
</GridItem>
</GridContainer>
</div>
</div>
);
}
}
先感谢您!!!
解决方案
posts
未在您的渲染函数中定义。你的意思是this.state.posts
?
此外,如果您的函数中已经有post
可用的单曲,则无需使用索引来访问帖子。map
所以posts[i].id
改为post.id
.
推荐阅读
- mysql - 如何在新表中导入列类型 json?
- css - 如何使 Angular Material 响应式?
- json - 我试图将我的嵌套 json 文件存储到 db 但它在索引中引发错误
- android - 无法断言共享首选项数据
- arrays - 用C中的多个文本文件的单词填充动态二维数组
- python - UMAP / HDBSCAN 增强集群 - 官方教程 - 错误:“工人的退出代码是 {EXIT(1)}”
- bootstrap-4 - 我可以使用引导程序在 div 内显示网格或表格吗
- php - 如何在循环时在 PHP 中添加多个条件
- r - 使用 R 中数据框列表中的 tidymodel 进行引导
- email - 带有 dovecot LMTP 的 Postfix 添加了没有 IP 地址的已接收标头