React项目出现TypeError: Cannot read properties of undefined (reading 'map')如何解决?
问题描述
我已尝试自行排查该问题,但未能定位到核心bug的位置,以下是报错结果和对应代码:
原始代码:
import React from "react"; import Ingredient from "../Ingredient/Ingredient"; import './Burger.css'; const Burger = (props) => { let ingredientArr = props.ingredients.map(item => { let amountArr = [...Array(item.amount).keys()] return amountArr.map( _ => { return <Ingredient type= {item.type} key= {Math.random()} /> }) })
核心bug定位
- 嵌套遍历返回二维数组:两层
map遍历后得到的ingredientArr是嵌套数组结构,React渲染时无法直接识别嵌套数组的元素,会导致渲染异常 - key值使用错误:用
Math.random()作为Ingredient组件的key,每次渲染key都会变化,会触发组件强制卸载重渲染,严重时会出现状态丢失、渲染错位的问题 - 未做参数兜底:没有对入参
props.ingredients做空值判断,如果外部传入undefined或者null,调用map方法会直接抛出报错
修复后代码
import React from "react"; import Ingredient from "../Ingredient/Ingredient"; import './Burger.css'; // 可选,引入prop-types做参数类型校验 import PropTypes from 'prop-types'; const Burger = (props) => { // 入参兜底,避免空值调用map报错 const ingredients = props.ingredients || []; // 用flat()把二维数组拍平为一维数组 let ingredientArr = ingredients.map(item => { let amountArr = [...Array(item.amount).keys()] return amountArr.map((_, index) => { // 用稳定的组合值作为key,保证同一物料同一序号下key唯一且稳定 return <Ingredient type={item.type} key={`${item.type}-${index}`} /> }) }).flat(); // 渲染逻辑示例 return ( <div className="burger"> {ingredientArr} </div> ) } // 可选,添加参数类型校验和默认值 Burger.propTypes = { ingredients: PropTypes.arrayOf(PropTypes.shape({ type: PropTypes.string.isRequired, amount: PropTypes.number.isRequired })) } Burger.defaultProps = { ingredients: [] } export default Burger;
内容的提问来源于stack exchange,提问作者Bachan Kubi
相关产品推荐
相关产品推荐

