React Router路由传参后Payment组件filter匹配失效报image未定义
Payment组件数据匹配问题修复方案
问题根源
原Payment组件的过滤逻辑匹配了错误的数据层级:
- 导入的
data.json根数组仅包含1个分类容器对象,该对象下挂载freetoplay、action两个商品数组,本身不存在id、image、price、name这类商品字段 - 原代码直接对根数组执行
product.id === productId的匹配,最终拿到的filteredData是undefined,后续对不存在的对象读取image属性,就会触发image not defined的报错
正确的过滤实现
需要先穿透分类容器层级,合并所有商品为统一列表后,再匹配路由传入的productId,修改后的完整代码如下:
import React from 'react' import { useParams, Link } from "react-router-dom"; import data from "../data.json"; function Payment() { const { productId } = useParams(); // 取到JSON根数组里的分类容器对象 const categoryContainer = data[0]; // 合并两个分类下的所有商品为统一数组 const allProducts = [ ...categoryContainer.freetoplay, ...categoryContainer.action ]; // 匹配对应ID的商品 const filteredData = allProducts.find(product => product.id === productId); // 增加空值兜底,避免无效ID导致页面崩溃 if (!filteredData) { return <div className='Payment'>商品不存在</div> } return ( <div className='Payment'> <img src={filteredData.image} alt={filteredData.name} /> <h1>{filteredData.price}</h1> <h1>{filteredData.name}</h1> </div> ) } export default Payment
修改要点
- 不再直接对根JSON数组做商品匹配,先穿透分类层级拿到真实商品集合
- 用语义更清晰的
find方法替代原filter(...)[0]的写法 - 增加空值兜底逻辑,路由传入无效商品ID时不会直接白屏
注意事项
当前测试JSON里的商品
image字段值为占位符"src=fsdf",实际部署时需要替换为有效的可访问图片路径
内容的提问来源于stack exchange,提问作者Tequila
相关产品推荐
相关产品推荐

