【问题标题】:Nested array with React and Firestore - How to display?带有 React 和 Firestore 的嵌套数组 - 如何显示?
【发布时间】:2021-09-20 13:37:45
【问题描述】:

我在集合中的各个项目中有一个嵌套数组。

{
"id": "RpFRcKLIgELlBLgIOJM4",
"Category": "",
"Method": "",
"User": "rWFZhAKk9eOSIIFoP0DqqvrC6WJ3",
"Foods": [
    {
        "Weight": 1.065,
        "label": "Milk - Long Life (1 Litre) (1.065)",
        "value": "Milk-LongLife(1Litre)"
    },
    {
        "label": "Blueberries (0.125)",
        "value": "Blueberries",
        "Weight": 0.125
    }
],
"Name": "456",
"Serves": ""
}
{
"id": "WQ6KBLevFsCdV73j4KU4",
"Category": "",
"Name": "123",
"Foods": [
    {
        "value": "Wine-White",
        "label": "Wine - White"
    },
    {
        "value": "Milk-LongLife(1Litre)",
        "label": "Milk - Long Life (1 Litre)"
    }
],
"Serves": "",
"User": "rWFZhAKk9eOSIIFoP0DqqvrC6WJ3",
"Method": ""
}
const useItemsMeals = () => {
const user = firebase.auth().currentUser;
const user1 = user.uid;
  const [items, setItems] = useState([]); //useState() hook, sets initial state to an empty array
  useEffect(() => {
    const unsubscribe = firebase
      .firestore()
      .collection("meals")
      .where("User", "==", user1)
      .orderBy("Category", "asc")
      .onSnapshot(snapshot => {
        const listItemsMeals = snapshot.docs.map(doc => ({
          id: doc.id,
          ...doc.data()
        }));
        setItems(listItemsMeals);
        console.log(listItemsMeals);
      });
    return () => unsubscribe();
  }, []);
  return items;
};

我很难显示“食物”数组中的项目,目前正在用于我的退货:

const listItemMeals = useItemsMeals();
{listItemMeals.map(item => (
      <TableRow hover key={item.id} id={item.id}>
      <TableCell>{item.Category}</TableCell>
      <TableCell>{item.Name}</TableCell>
      <TableCell>{item.Foods}</TableCell>

这样做时它告诉我:

错误:对象作为 React 子对象无效(找到:带有键 {label, value} 的对象)。如果您打算渲染一组子项,请改用数组。

我想我需要以某种方式再次映射这个嵌套数组 - 但对于我的生活 - 无法弄清楚!

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore


    【解决方案1】:

    你快到了。

    您的 useItemsMeals 函数从 Firestore 加载数据,并将其正确设置到状态下的 items 变量中以呈现它。但是你在渲染代码中使用了const listItemMeals = useItemsMeals(),这就搞砸了。

    您不应尝试从useItemsMeals 返回任何值,而应仅依靠状态中的items 变量在数据库和渲染之间传递信息。

    所以:

    // return items; ? remove this
    ---
    // const listItemMeals = useItemsMeals(); ? remove this
    ---
    {items.map(item => ( // ? read items from the state instead
    

    【讨论】:

    • 谢谢弗兰克-如果我按照您上面提到的“第 75:8 行:'items' 未定义 no-undef”来执行此操作,我会收到错误消息......这一行“{items.map(项目 => ("
    • 您需要确保在某处声明了const [items, setItems] = useState([]);,以便您的渲染代码也可以访问items
    • 不知道该怎么做 Frank(抱歉,正在学习 React)——如果我添加 const [items, setItems] = useState([]);到这个 const ItemListMeals = ({ editItem }) => { 然后它编译但没有显示数据
    • reactjs.org/docs/hooks-state.html。他们在功能组件中调用useState,但在任何数据加载方法之外,以便您的onSnapshot 侦听器和您的渲染代码都可以访问它。
    • Frank - 你能提供一些代码吗?我已尝试完成,但未成功!
    【解决方案2】:

    您需要再次循环遍历 Foods 数组。像这样

    const listItemMeals = useItemsMeals();
    {listItemMeals.map(item => (
          <TableRow hover key={item.id} id={item.id}>
          <TableCell>{item.Category}</TableCell>
          <TableCell>{item.Name}</TableCell>
          {
           item.Foods.map(food=>(
               <div> //this can div or a new row tag
                   <TableCell>{food.weight}</TableCell>
                   <TableCell>{food.label}</TableCell>
                   <TableCell>{food.value}</TableCell>
               </div>))
          }
          
    

    【讨论】:

    • 感谢 RobLjm - 这就是我得到“TypeError: item.Foods.map is not a function”错误的地方
    • 那么“item.Foods”要么不是数组,要么是未定义的。 console.log(items) 或使用 react 开发工具在渲染前检查“items”的值
    • 根据我在问题中的数组转储 - 似乎 Foods 是一个数组...
    • “错误:对象作为 React 子对象无效(找到:带有键 {label, value} 的对象)。如果您要呈现子对象集合,请改用数组。”此错误表明您至少在组件内获取了 Foods 数组,但无法呈现此类对象。如果我建议的代码不起作用,我只能在您将代码暂存到类似代码和框的地方时提供帮助
    猜你喜欢
    • 1970-01-01
    • 2020-03-30
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 2020-04-01
    • 2018-01-19
    • 2010-09-15
    • 2019-02-04
    相关资源
    最近更新 更多