React项目出现Uncaught TypeError报错,页面空白如何解决?
解决React项目中Uncaught TypeError的问题
问题描述
跟随React视频教程开发项目,完全按教程操作后页面显示空白,控制台抛出两个错误:
Uncaught TypeError: this.props.products.map is not a functionUncaught TypeError: Cannot read properties of undefined (reading 'map')
错误均发生在<CategoryList>组件中,使用db.json作为数据源。
错误原因及修复方案
1. CategoryList组件错误读取props中的categories
CategoryList的分类数据存储在自身state中,但render时错误尝试读取this.props.categories,而App组件并未传递该props,导致undefined.map报错。
修复CategoryList.js的render部分:
将this.props.categories.map替换为this.state.categories.map:
{this.state.categories.map(category => ( <ListGroupItem onClick={() => this.props.changeCategory(category)} key={category.id}> {category.categoryName} </ListGroupItem> ))}
2. CategoryList组件错误调用state中的changeCategory
点击事件中错误调用this.state.changeCategory,但changeCategory是父组件App通过props传递的方法,应使用this.props.changeCategory。
修复CategoryList.js的onClick事件:
上述代码已同步修复该问题,将this.state.changeCategory(category)改为this.props.changeCategory(category)。
3. App组件中getProducts函数的URL拼接错误
拼接带categoryId的URL时缺少等号,导致请求URL格式错误(如http://localhost:3000/products?categoryId1),服务器返回非数组数据,引发products.map is not a function错误。
修复App.js的getProducts函数:
getProducts = categoryId => { let url="http://localhost:3000/products"; if(categoryId){ url += "?categoryId=" + categoryId; // 补充等号修正参数格式 } fetch(url) .then(response => response.json()) .then(data => this.setState({ products: data })); }
4. 可选:添加数据存在性校验(预防潜在错误)
为避免请求返回非数组/undefined的情况,可在map前添加可选链操作符:
- ProductList.js中:
{this.props.products?.map(product => ( // 原有表格行代码 ))}
- CategoryList.js中:
{this.state.categories?.map(category => ( // 原有分类项代码 ))}
内容的提问来源于stack exchange,提问作者white
相关产品推荐
相关产品推荐

