【问题标题】:How to fix the state update in react while getting data from firestore database如何在从 Firestore 数据库获取数据时修复状态更新
【发布时间】:2019-02-08 13:38:24
【问题描述】:

我正在尝试从 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

我的 Firestore 集合中有两个文档。我希望在组件加载后,componentdidMount 将为 mapdata 执行 setstate。更新后的状态将重新渲染组件。但是 this.state.mapdata 中的更新状态不会重新渲染组件。所以 this.state.mapdata 的长度始终为 0,并且永远不会改变数据库中存在的数据量为 2。

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore state react-leaflet


    【解决方案1】:

    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
            });
        });    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-01
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      • 1970-01-01
      • 2017-12-30
      • 2021-05-19
      相关资源
      最近更新 更多