You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 07:24:02