在与FireBase反应中使用贴图

本教程将介绍在与FireBase反应中使用贴图的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

在与FireBase反应中使用贴图 教程 第1张

问题描述

谁来帮帮忙。我已经梳理了所有的文档,检查了所有类似的问题,真的看不到我遗漏了什么。

我是第一次进行反应,并尝试映射从Firebase数据库异步调用返回的文档。

代码如下:

class Posts extends React.Component {
constructor(props) {
 super(props);
 this.state = {
  data: [],
 };
}
componentDidMount() {
 let posts = [];
 db.collection("Posts").get().then(function(querySnapshot) {
  querySnapshot.forEach(function(doc) {
posts.push({
 data: doc.data(),
 id: doc.id
});
  });
 });
 this.setState({
  data: posts
 });
}
renderPosts() {
 console.log(this.state.data);
 return this.state.data.map((post, index) => {
  console.log(post);
  console.log(index);
  return (
<div>
 {index}
</div>
  )
 })
}
render() {
 return(
  <div>
{this.renderPosts()}
  </div>
 );
}
}

我确信这是非常简单的事情,但我正在拔掉我的头发。如果我检查我的状态,我可以看到数据。console.log(this.state.data);Inside renderPosts甚至精确地显示了我需要映射的内容,但是map回调中的所有内容都不会返回,我最终得到了一个空的结果,任何帮助都将不胜感激。

推荐答案

如Li357所评论,setState调用需要在get()回调中进行:

db.collection("Posts").get().then(function(querySnapshot) {
 querySnapshot.forEach(function(doc) {
  posts.push({
data: doc.data(),
id: doc.id
  });
 });
 this.setState({
  data: posts
 });
});

这是因为数据是从FiRestore异步加载的,并且在您调用setState时,posts变量仍然为空。

理解这种类型的异步加载的最简单方法是使用几行日志:

console.log("Before starting to get documents");
db.collection("Posts").get().then(function(querySnapshot) {
 console.log("Got documents");
});
console.log("After starting to get documents");

运行此命令时,输出为:

开始获取文档前

开始获取单据后

已获取文档

这可能不是您预期的输出顺序。但这是预期的行为:不是在加载数据时阻塞代码(这会冻结浏览器),而是立即执行get().then()挡路之后的代码。然后在加载数据时,执行then回调中的代码。这就是需要数据库文档的所有代码都需要在then回调中的原因。

好了关于在与FireBase反应中使用贴图的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。