React结合Firestore开发:如何正确渲染集合文档内的嵌套Foods数组
问题解决
错误原因
直接渲染item.Foods属于直接将JS对象作为React子元素,React本身不支持这种写法,因此抛出对应报错。
解决代码
你只需要对Foods嵌套数组做二次遍历渲染即可,以下提供两种常用的展示方案:
方案1:每行展示一个食物(带重量,展示清晰)
const listItemMeals = useItemsMeals(); {listItemMeals.map(item => ( <TableRow hover key={item.id} id={item.id}> <TableCell>{item.Category}</TableCell> <TableCell>{item.Name}</TableCell> <TableCell> {/* 遍历嵌套的Foods数组 */} {item.Foods?.map(food => ( <div key={food.value}> {food.label} {/* 存在重量则展示 */} {food.Weight ? `(${food.Weight})` : ''} </div> ))} </TableCell> {/* 其余TableCell代码保持不变 */} </TableRow> ))}
方案2:逗号分隔展示(节省表格空间)
如果你不需要每行展示一个食物,可以直接拼接为字符串展示:
<TableCell> {item.Foods?.map(food => food.Weight ? `${food.label}(${food.Weight})` : food.label ).join('、')} </TableCell>
优化建议
你封装的useItemsMeals自定义Hook缺少未登录场景兼容,建议调整为以下写法避免用户未登录时访问页面直接报错:
const useItemsMeals = () => { const [items, setItems] = useState([]); useEffect(() => { // 先判断当前是否有登录用户 const user = firebase.auth().currentUser; if (!user) return; const unsubscribe = firebase .firestore() .collection("meals") .where("User", "==", user.uid) .orderBy("Category", "asc") .onSnapshot(snapshot => { const listItemsMeals = snapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })); setItems(listItemsMeals); }); return () => unsubscribe(); }, []); return items; };
内容的提问来源于stack exchange,提问作者Paul VI
相关产品推荐
相关产品推荐

