如何循环 return javascript 对象的值?

How to loop through and return the values of a javascript object?

(如果我的某些术语不正确,请见谅)

在 Firebase 中,我有许多 post。每个 post 都有一个 'latitude' 字段和一个 'longitude' 字段。我将它们取出并存储在一个名为 mapRefs:

的 array/object 中
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>

这是行不通的。请问正确的做法是什么?

您需要使用 state values 来渲染 UI 元素,并且 mapRefsuseEffect 之外不可用。

这样试试

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