React中如何渲染products.productId下的title与img至表格?
问题根源
你额外维护的myProductTitle状态是核心问题:遍历订单数据时,每次调用setmyProductTitle都会覆盖之前的值,最终这个状态只会保留最后一个遍历到的产品信息,导致所有表格行都显示同一个产品。
解决方案
不需要单独存储产品信息,直接利用订单数据中已有的products.productId字段进行渲染即可,具体修改如下:
1. 简化状态与请求逻辑
移除多余的产品状态,直接保留订单数据状态:
const [recentTransaction, setRecentTransaction] = useState([]) // 移除myProductTitle相关的状态声明 useEffect(() => { const getStats = async () =>{ const res = await userRequest.get(`/order/recent/${id}`) // 移除多余的嵌套map和setmyProductTitle操作 setRecentTransaction(res.data) setLoading(false) } getStats() },[id])
2. 修正表格渲染代码
针对每个订单,直接遍历其自带的products数组,渲染对应产品的title和img(支持单个订单包含多个产品的场景):
{recentTransaction.map((recent) => ( <TableRow key={recent._id}> <TableCell component="th" scope="row"> {recent._id} </TableCell> <TableCell align="left"> {recent.userId.firstname} {recent.userId.lastname} </TableCell> <TableCell align="left">{recent.userId.studentId}</TableCell> <TableCell align="left"> {/* 遍历当前订单的产品列表,渲染每个产品的信息 */} {recent.products.map((productItem) => ( <Box key={productItem._id} sx={{display: 'flex', alignItems:'center', marginBottom: '8px'}} > <Typography mr={1}>{productItem.productId.title}</Typography> <Box component="img" sx={{width: '50px'}} src={productItem.productId.img} alt={productItem.productId.title} /> </Box> ))} </TableCell> <TableCell align="left">₱ {recent.amount}</TableCell> <TableCell align="left" sx={{display:'flex', alignItems:'center', borderRadius: '5px'}}> <Typography sx={{padding:1, backgroundColor: 'yellow'}}> {recent.status} </Typography> </TableCell> </TableRow> ))}
修改后,每个表格行都会绑定对应订单的产品数据,不会再出现所有行显示同一产品的问题。
内容的提问来源于stack exchange,提问作者Stykgwar
相关产品推荐
相关产品推荐

