简体   繁体   English

React.js,如何正确使用map()函数显示数据?

[英]React.js, how to properly use the map() function to display data?

I'm tying to display user data in one of my pages in an electron app.我想在电子应用程序的一个页面中显示用户数据。 I get the data from firebase/firestore and then put it in an array, then, I want to display that data in a table but I can't manage to display the data on the page.我从 firebase/firestore 获取数据,然后将其放入数组中,然后,我想在表格中显示该数据,但无法在页面上显示数据。

Here is my code :这是我的代码:

function Home() {
  const [allUsers] = useState([]);
  useEffect(() => {
    const fetchData = async () => {
      try {
        const querySnapshot = await getDocs(collection(db, 'users'));
        let allDocs = [];
        querySnapshot.forEach((doc) => {
          allDocs.push({ ...doc.data(), id: doc.id });
        });
        for (const item of allDocs) {
          allUsers.push(item);
        }
      } catch (err) {
        console.log(err);
      }
      console.log(allUsers)
    };
    fetchData();
  }, []);


  return <div className="home">
    {Object.keys(allUsers).map((keyName) => (         
    <p>{allUsers[keyName].firstname}</p>
    ))}
  </div>;
}

Here is how the data looks like :以下是数据的样子:

数据

You should be using a state setter to update allUsers .您应该使用状态设置器来更新allUsers You are mutating data (anti React pattern).您正在改变数据(反 React 模式)。 Try doing so (I added comments in the code):尝试这样做(我在代码中添加了注释):

function Home() {
  const [allUsers, setAllUsers] = useState([]); // line I changed
  useEffect(() => {
    const fechedUsers =[];  // line I added
    const fetchData = async () => {
      try {
        const querySnapshot = await getDocs(collection(db, 'users'));
        let allDocs = [];
        querySnapshot.forEach((doc) => {
          allDocs.push({ ...doc.data(), id: doc.id });
        });
        for (const item of allDocs) {
          fechedUsers.push(item);
        }
      } catch (err) {
        console.log(err);
      }
      setAllUsers(fechedUsers) // line I added
    
    };
    fetchData();
  }, []);

  // lines I changed
  return <div className="home">
    {allUsers.map(user => <p>{user.firstname}</p>)}
  </div>;
}

Currently you use Object.keys() to map over the array.目前您使用Object.keys()来映射数组。 When you use this function you receive an array with all the indexes off the array.当您使用此函数时,您会收到一个数组,其中包含数组中的所有索引。 So this means you will get an array with the data [0, 1, ... ] depending on the length of the data.因此,这意味着您将获得一个包含数据[0, 1, ... ]的数组,具体取决于数据的长度。

But because you use an array you can immediately map over all the objects in the array.但是因为您使用数组,您可以立即映射数组中的所有对象。 Like this:像这样:

return <div className="home">
    {allUsers.map((user) => (         
        <p>{user.firstname}</p>
    ))}
</div>

The user variable will be the object you have pushed in the allUsers array.用户变量将是您在 allUsers 数组中推送的对象。 You should also use a state setter like useState您还应该使用像useState这样的状态设置器

You don't need to use the index to iterate over the response.您不需要使用索引来迭代响应。 When you use the map function, you get access to the index as a parameter inside the map function and can use it if needed.当您使用 map 函数时,您可以访问索引作为 map 函数内部的参数,并且可以在需要时使用它。

 return (
       <div className="home">
        {allUsers.map((user, index) => {  
          return(
             <div  key={index} className='user-data'>
              //if you're using a table might  need to change the  `p` tag with `td` inside a `tr`
              <p>{user.firstname} </p>
             </div>
           )
        }
        )}
      </div>);

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

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