简体   繁体   中英

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.

在此处输入图片说明

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. That means if you put that code in react and use {} around it it won't return anything.

To make it work use a state and 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>
  );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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