React开发:可获取props传入的selectedDish对象,访问其内部属性却返回undefined
问题根因
- 自定义组件的入参接收存在本质认知偏差
所有React函数组件的形参,永远是一个包含所有标签属性的props对象,不会直接把你在标签上写的属性值当作函数入参。
你写的<RenderDish dish={props.selectedDish}/>,传入RenderDish的真实入参是{ dish: 你的selectedDish对象 },并非你预期的selectedDish本身。你在RenderDish里直接打印整个形参时,能看到嵌套在里面的完整dish内容;但直接访问形参上的name/comments字段时,实际访问的是最外层props包裹层的属性,这层根本没有这些字段,所以打印结果全是undefined。 - 评论遍历的逻辑存在索引错位
你在RenderComments的for循环里,每次循环取出的单条评论是info[i],但后续访问评论内容、作者、时间字段时,依然直接用整个数组对象info取值,哪怕外层的props包裹问题修好,这里也无法获取到正确的单条评论数据。
代码修正要点
- 给RenderDish补充props解构逻辑,从外层props里取出真正的dish实体:
function RenderDish(props) { const { dish } = props; // 从props中解构出嵌套的dish对象 console.log(dish.name) // 此时就能正确取到字段值 // 原有的Card渲染逻辑保持不变 return ( <Card key={dish.id}> <CardImg top src={dish.image} alt={dish.name}/> <CardBody> <CardTitle> <b>{dish.name}</b> </CardTitle> <CardText> {dish.description} </CardText> </CardBody> </Card> ); } - 给RenderComments补充props解构逻辑,同时修正循环内的字段访问来源,替换非标准HTML标签:
function RenderComments(props) { const info = props.info; // 从props中解构出嵌套的评论数组 if (info != null) { const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]; let commentsArray = []; for (let i = 0; i < info.length; i++) { const currentComment = info[i]; // 取出当前循环对应的单条评论 if (currentComment != null) { commentsArray.push(currentComment.comment); commentsArray.push("\n") let date = new Date(currentComment.date) commentsArray.push(`-- ${currentComment.author}, ${monthNames[date.getMonth() + 1]} ${date.getDay()}, ${date.getFullYear()}`) commentsArray.push("\n"); } else { return <div></div> } } // 替换原代码中非标准的<p1>标签为普通div return ( <div> <h4> Comments </h4> <div> {/* 给map渲染的元素补充key,避免React渲染警告 */} {commentsArray.map((line, idx) => <p key={idx}>{line}</p>)} </div> </div> ) } return <div></div> }
内容的提问来源于stack exchange,提问作者Marcooz2007
相关产品推荐
相关产品推荐

