如何修复从 firestore 数据库获取数据时反应中的状态更新

Nik*_*ala 2 state firebase reactjs react-leaflet google-cloud-firestore

我正在尝试从 firestore 数据库获取数据并将其显示在组件中。我已经与数据库建立了连接。我可以在控制台日志中查看数据库中的数据。但我似乎无法在组件初始构建后更新反应组件状态。我是个新手,无法做出反应,不知道发生了什么。下面是我的组件代码。

我尝试将数据库调用移至子组件。并且有同样的问题。我尝试构建具有初始状态的组件,该状态看起来像数据库中的数据。我尝试删除对标记数据的检查以验证它是否未定义。而且我仍然不明白问题出在哪里。

import React, { Component } from 'react'
import { Map, TileLayer } from 'react-leaflet'
import MarkerList from './MarkerList'
import './Basemap.css'
import firebase from '../../config/fbConfig'

class Turmap extends Component {
constructor(){
super();
this.state={
  mapdata:[]
}
};

componentDidMount(){
 const db = firebase.firestore();
 var turmarkers =[];

db.collection("Markets").get().then((querySnapshot) => {
  querySnapshot.forEach((doc) => {        
    turmarkers.push(doc.data())

  })
}
);    
  this.setState({
    mapdata:turmarkers
   }) 
}

render() {

var markers  = this.state.mapdata;    
return (
  <div>
    {this.state.mapdata.length}
      <Map className='map' center={[21,79]} zoom={4.3}>
      <TileLayer
      attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
    />
          {this.state.mapdata.length>0 && <MarkerList markers = {markers} />}  

      </Map>

  </div>
)
 }
 }
 export default Turmap
Run Code Online (Sandbox Code Playgroud)

我的 firestore 收藏中有两份文档。我预计组件加载后,componentdidMount将为mapdata执行setstate。更新后的状态将重新渲染组件。但是 this.state.mapdata 中更新的状态不会重新渲染组件。因此 this.state.mapdata 的长度始终为 0,并且永远不会更改数据库中存在的数据量(即 2)。

Moh*_*ami 5

移动this.setState到数据库回调内部(如果将其放在外部,它将在数据库调用完成之前执行)

componentDidMount() {
    const db = firebase.firestore();
    var turmarkers =[];

    db.collection("Markets").get().then((querySnapshot) => {
        querySnapshot.forEach((doc) => {        
            turmarkers.push(doc.data())

         });

        this.setState({
            mapdata:turmarkers
        });
    });    
}
Run Code Online (Sandbox Code Playgroud)