React点击Load More时报错Cannot read properties of undefined (reading 'id')
问题原因
报错核心是变量引用错误,对应render方法内的map遍历逻辑:
你已经在map回调中拿到了当前遍历的元素对象post,但后续给PostCard组件传参时,错误使用了未声明的posts[i]:
- 你的
render函数中没有定义过名为posts的变量,你要访问的是挂载在this.state下的posts数组 - 更高效的写法是直接使用
map回调返回的当前元素post,不需要再通过索引去数组内重复取值
三次点击后才触发报错,是因为初始visible值为3,三次点击后visible变为12,刚好超出了你测试环境下可能存在的临时posts变量的长度,触发了undefined读取id的错误。
修正方案
直接替换map遍历段的参数引用即可,修正后的完整代码如下:
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) => { return ( <PostCard key={post.id} id={post.id} date={post.date} fbimg={post.fbimg} description={post.description} fbpost={post.fbpost} /> ); }) } </GridContainer> <GridContainer> <GridItem> {this.state.visible < this.state.posts.length && <Button color="info" onClick={this.loadMore} > Load more </Button> } </GridItem> </GridContainer> </div> </div> ); } }
可选优化建议
- 不要使用数组索引作为列表项的
key值,当列表新增/删除项时可能引发组件状态错乱、性能损耗,直接用post.id作为key更合适 - 可以在
fetch拿到返回结果后先做一层数据格式校验,避免后端返回字段缺失引发的渲染错误
内容的提问来源于stack exchange,提问作者Shpongle
相关产品推荐
相关产品推荐

