【问题标题】:How can I display the data with a true inside the object?如何在对象内部显示具有 true 的数据?
【发布时间】:2021-08-29 07:17:17
【问题描述】:

从 firestore 获取用户集合:

 useEffect(() => {
        if (currentUser) {
          const unsubscribe = db
            .collection("users")
            .doc(uid)
            .onSnapshot((snapshot) => {
          const arr = [];
          arr.push({
            ...snapshot.data(),
          });

          setUsers(arr);
          console.log(JSON.stringify(arr));
        });

      return () => {
        unsubscribe();
      };
    }
  }, [currentUser]);

这就是我console.log(JSON.stringify(arr))的地方;

[
  {
    1: { others: "books", items: { Item1: true, Item2: true } },
    2: {
      items: { Item3: true, Item2: true },
      others: "books",
    },

    displayName: Inigi,
    address: "US",
  },
];

我怎样才能像这样显示那些items

  • 项目1
  • 项目2

这些是代码,但我有这个错误:

 {user["1"]?.items.map((index) => (
              <li>{index.Item1}</li>
            ))}

错误:

TypeError: _user$.items.map 不是函数

使用这些代码,没有错误,但不显示任何内容:

{user["1"]?.items?.map?.((index) => (                   
     <li>{index.Item1}</li>                 
 ))}

【问题讨论】:

标签: javascript reactjs firebase google-cloud-firestore


【解决方案1】:

Map 是一个数组函数,你的数据类型是一个对象。

typeof user["1"]?.items == object

这意味着您必须使用 for..in 或任何您喜欢的方式迭代对象。

例子:

 const firestoreResponse = [
    {
        1: { others: "books", items: { Item1: true, Item2: true } },
        2: {
          items: { Item3: true, Item2: true },
          others: "books",
        },
    
        displayName: '',
        address: "US",
      },
 ]

//Destructure relevant data
const obejctItems = firestoreResponse[0][1].items
//Iterate the items object
for(let item in obejctItems){
    console.log(item)
}

输出:项目1,项目2

【讨论】:

    【解决方案2】:

    假设您有以下数据:

    onst data = [
      {
        1: { others: "books", items: { Item1: true, Item2: true } },
        2: {
          items: { Item3: true, Item2: true },
          others: "books",
        },
    
        displayName: Inigi,
        address: "US",
      },
    ];
    

    您可以按如下方式访问每个用户:

    const user1 = x[0][1];
    const userItems1 = x[0][1].items;
    

    然后你可以遍历它的项目并使用它们,例如我已经制作了一个这个数据的数组:

    let ar=[];
    for (const [key, value] of Object.entries(userItems1)) {
      ar.push(value);
      console.log(`${key}: ${value}`);
    }
    

    然后您可以将此数组映射到任何组件,例如li

    【讨论】:

    • @Abbasihn 谢谢,现在可以了。就是这样,您知道为什么每次我重新加载页面时都会出现TypeError: Cannot read property '1' of undefined 的错误吗?
    • 很高兴听到,您是否考虑过 api 调用的 async 行为?如果是,你可以使用?运算符。
    猜你喜欢
    • 2021-01-11
    • 1970-01-01
    • 2018-08-14
    • 2021-10-09
    • 1970-01-01
    • 2020-07-11
    • 2021-12-23
    • 2019-11-24
    • 2020-10-14
    相关资源
    最近更新 更多