当我使用useEffect和setState时,React组件不会重新渲染

时间:2020-01-31 15:47:49

标签: javascript reactjs leaflet react-leaflet use-effect

我正在编写带有react-leaflet映射库的react应用程序。但是,当我使用useEffect从Firestore中获取数据时,成功获取数据后,地图组件根本不会重新呈现。

这是我的代码:

import React, { useState, useEffect } from 'react'
import { Map, TileLayer, Marker, Popup } from 'react-leaflet';
import "./App.css";
import firebase from "firebase";

export default function LeafletMapContainer(props) {

    const [storeData, setStoreData] = useState([]);
    const [centre, setCentre] = useState([22.3193, 114.1694])
    const config = {
        ...
    }

    const app = firebase.initializeApp(config);

    useEffect(() => {
        const fetchData = () => {
            let tmp = []
            const db = firebase.initializeApp(config).firestore();
            const query = db.collection("store").get().then(snapshot => {
                snapshot.forEach(doc => {
                    tmp.push(doc.data());
                })
            })
            setStoreData(tmp);
        }
        fetchData();
    }, [])

    return (
        <Map center={centre} zoom={12}>
            <TileLayer
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            />
            {
                storeData.map(x => {
                    console.log([x.store_geo.latitude, x.store_geo.longitude])
                    if (!x.has_stock) {
                        return (
                            <Marker position={[x.store_geo.latitude, x.store_geo.longitude]}>
                                <Popup>
                                    A pretty CSS3 popup. <br /> Easily customizable.
                                </Popup>
                            </Marker>
                        )
                    } else {
                        return (
                            <Marker position={[x.store_geo.latitude, x.store_geo.longitude]}>
                                <Popup>
                                    A pretty CSS3 popup. <br /> Easily customizable.
                                </Popup>
                            </Marker>
                        )
                    }
                })
            }
        </Map>
    )
}

我还尝试通过使用道具从父级传递storeData,但是它也不起作用。

0 个答案:

没有答案