喵喵時光機
2023-06-29 21:15:55
(如果我的某些條款不正確,請道歉)在 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>這不起作用。請問這樣做的正確方法是什么?
1 回答

紫衣仙女
TA貢獻1839條經驗 獲得超15個贊
您需要使用狀態值來呈現 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>
)
添加回答
舉報
0/150
提交
取消