(抱歉,如果我的某些说法不正确)
在Firebase中,我有很多帖子。每个帖子都有一个“纬度”字段和一个“经度”字段。我将它们拉出并存储在名为mapRefs的数组/对象中:
useEffect(() => {
projectFirestore.collection("posts").get().then(res => {
let mapRefs = [];
res.forEach(data => {
mapRefs.push([data.data().myLatitude, data.data().myLongitude]);
});
console.log(mapRefs);
});
}, []);
这有效,控制台日志的输出为:
0: (2) [-8.6848548, 115.22303799999999]
1: (2) [-8.7848548, 115.323038]
2: (2) [-8.9848548, 115.52303799999999]
3: (2) [-8.8848548, 115.42303799999999]
然后我如何遍历这些并将纬度和经度值映射到组件。我正在尝试这样:
<ReactMapGL>
{ mapRefs && mapRefs.map(coord => (
<Marker latitude={coord[0]} longitude={coord[1]}>
<div>
...
</div>
</Marker>
))}
</ReactMapGL>
这不起作用。请问正确的方法是什么?
答案 0 :(得分:2)
您需要使用state values来呈现UI元素,并且mapRefs
在useEffect
之外不可用。
尝试这样
const [mapRefs, setMapRefs] = useState([])
useEffect(() => {
projectFirestore.collection("posts").get().then(res => {
let refs = [];
res.forEach(data => {
refs.push([data.data().myLatitude, data.data().myLongitude]);
});
setMapRefs(refs)
});
}, []);
return (
<ReactMapGL>
{ mapRefs.map(coord => (
<Marker latitude={coord[0]} longitude={coord[1]}>
<div>
...
</div>
</Marker>
))}
</ReactMapGL>
)