【问题标题】:Map not working in an array but for each is working地图不在数组中工作,但每个都在工作
【发布时间】:2022-06-22 19:43:14
【问题描述】:

我正在创建一个使用 firebase cloud firestore 的 react 网站。这是我目前正在使用的代码(根据文档):

async function onTypeSelected(type = "Electronics") {
  var querySnapshot = await getDocs(collection(db, type))
  console.log(querySnapshot)
  querySnapshot.forEach(doc => {
    console.log(doc.data())
  })
}

此代码运行良好。我可以在控制台中看到输出:

但是,如果我使用 .map() 方法,我会收到错误:

async function onTypeSelected(type = "Electronics") {
  var querySnapshot = await getDocs(collection(db, type))
  console.log(querySnapshot)
  var a = querySnapshot.map(
    (doc) => {
      return <Card data={doc.data()} />
    }
  )

  console.log(a)
}

&lt;Card /&gt; 是我自己创建的另一个组件:

function Card(props) {
  return (
    <div className='main__container__card'>
      <img src={props.image} />
      <div style={{ marginTop: 20 }} />
      <hr />
      <div style={{ marginTop: 10 }} />
      <h2>{props.price}</h2>
      <div style={{ marginTop: 10 }} />
      <hr />
      <div style={{ marginTop: 10 }} />
      <div className='main__container__card__btn'>
        <CurrentQuantity />
      </div>
    </div>
  )
}

错误:

这里有什么错误?

如果需要更多信息,请发表评论。

【问题讨论】:

  • 你的querySnapshot 变量是一个对象而不是一个数组,这就是为什么你不能使用map
  • getDocs返回什么类型的数据?
  • 我相信这是因为 querySnapshot 是一个对象而不是一个数组。看看这个link
  • querySnapshot 是类似{{...}, {...}} 的对象,因此您不能使用 map 函数进行迭代。
  • 普通对象没有forEach,伙计们。返回类型至少是类似数组的。

标签: javascript reactjs


【解决方案1】:

看起来getDocs 没有返回Array,但类似数组的东西恰好有forEach。

很有可能您可以将其解构为一个数组,
试试这个:

var a = [...querySnapshot].map(
  (doc) => {
    return <Card data={doc.data()} />
  }
)

【讨论】:

    猜你喜欢
    • 2021-09-01
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 2012-10-31
    • 2014-01-02
    相关资源
    最近更新 更多