简体   繁体   English

reactjs如何在firebase上读取数组中的地图

[英]reactjs how can i read map in array on firebase

I have an array, and inside an array i have a map.我有一个数组,在一个数组中我有一张地图。 Map has 2 value, title and content.地图有 2 个值,标题和内容。

在此处输入图片说明

I want to read all values in array, but it should be like map.我想读取数组中的所有值,但它应该像地图一样。 I tried this code, but i can't do it.我试过这段代码,但我做不到。 Can you help me?你能帮助我吗?

{database.collection("notes")
          .doc(uid)
          .onSnapshot((doc) => {
            doc.data().notes.map((value, index) => {
              return (
                <Note
                  key={index}
                  id={index}
                  title={value.title}
                  content={value.content}
                  onDelete={deleteNote}
                />
              );
            });
          })}

finally, it should be like this:最后,它应该是这样的: 在此处输入图片说明

The problem with your code is that the onSnapshot uses a callback that will be executed like Future.您的代码的问题在于onSnapshot使用将像 Future 一样执行的callback That means if you put that code in react and use {} around it it won't return anything.这意味着如果您将该代码放入 react 并在其周围使用{} ,它将不会返回任何内容。

To make it work use a state and useEffect .要使其工作,请使用 state 和useEffect Your code could look like this:您的代码可能如下所示:


import React from "react";
import { useEffect } from "../../../github/ecronix/wc-csv-export/node_modules/@types/react";

const YourComponent = () => {
  const [list, setList] = useState([]);

  useEffect(() => {
    database
      .collection("notes")
      .doc(uid)
      .onSnapshot((doc) => {
        const tempList = [];
        doc.data().notes.map((value, index) => {
          tempList.push({ value, index });
        });

        setList(tempList);
      });
  });

  return (
    <div>
      {list.map(({ value, index }) => {
        return (
          <Note
            key={index}
            id={index}
            title={value.title}
            content={value.content}
            onDelete={deleteNote}
          />
        );
      })}
    </div>
  );
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM