【问题标题】:How Do I map through an object using react and firebase如何使用 react 和 firebase 映射对象
【发布时间】:2021-11-13 04:56:26
【问题描述】:

我正在创建一个动态用户配置文件并尝试使用 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对象进行映射并将数据显示给用户喜欢

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

但它一直在抛出

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

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore mapping typeerror


    【解决方案1】:

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

    find() 方法返回提供的数组中满足提供的测试功能的第一个元素的值

    所以返回值是数组中的一个元素,而不是数组本身,并且该对象没有map 方法。

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

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

    【讨论】:

    • 我试过那个方法,但是因为对象来自 API,它需要时间来加载和响应最初的渲染,所以当 react 检查它发现一个空对象然后抛出这个错误“TypeError:无法读取属性未定义(读取“名称”)“
    • 啊,这确实是第二个问题。您需要通过setState(或useState)传递项目,正如我在herehere 显示的那样。
    • 嘿@MinenhleSolsonCele 这里有更新吗?
    • 是的,谢谢你问我使用了条件渲染方法,{findTheUser ?

      {findTheUser.name}

      {findTheUser.email}

      : null}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    • 2017-09-11
    • 2023-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    相关资源
    最近更新 更多