如何使用 react 和 firebase 映射对象

How Do I map through an object using react and firebase

我正在创建一个动态用户配置文件,并且正在尝试使用 React 通过对象进行映射。

我在下面有这段代码可以获取用户数据:

   projectFirestore.collection("users").onSnapshot(snapshot => (
     setUserData(snapshot.docs.map(doc => doc.data()))
   ))
 }, [])
/*when the user data is fetched I console.log it
 console.log(userData)
and it returns an array with objects like [{…}, {…}, {…}, {…}, {…}]
*/

然后我使用 array.find() 方法搜索特定用户:

const findTheUser = userData.find(function(data, index) {
   if(data.email === 'minenhlecele@gmail.com')
     return true;
   });  

/* I console.log it
console.log(findTheUser)

and it returns the matching object. the result looks like this  */ 
//{name: 'Minenhle Cele', email: 'minenhlecele@gmail.com', photoUrl: 'https://lh3.googleusercontent.com/a-/AOh14Gj36jZuv0m2rxAN7Fx_78QWHbURpY-YeWb9g=s96-c'}

然后我要的是通过findTheUser对象映射,把数据显示给用户like

{findTheUser.map(({{ name, email}}) => (
           <div className="card">
             <h1>{name}</h1>
             <h2>{email}</h2>
           </div>
            ))}

但它一直抛出

TypeError: Cannot read properties of undefined (reading 'map')

您的 findTheUser 函数使用 Array.find 记录为:

The find() method returns the value of the first element in the provided array that satisfies the provided testing function

因此 return 值是数组中的一个元素,而不是数组本身,并且该对象没有 map 方法。

所以你不需要循环,可以这样做:

<div className="card">
  <h1>{findTheUser.name}</h1>
  <h2>{findTheUser.email}</h2>
</div>