简体   繁体   中英

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

(Apologies if some of my terms aren't correct)

In Firebase I have a number of posts. Each post has a 'latitude' field and a 'longitude' field. I am pulling these out and storing them in an array/object called mapRefs:

useEffect(() => {
    projectFirestore.collection("posts").get().then(res => {
        let mapRefs = [];
        res.forEach(data => {
            mapRefs.push([data.data().myLatitude, data.data().myLongitude]);    
        });
        console.log(mapRefs);

        });
}, []);

This works, the output for the console log is:

0: (2) [-8.6848548, 115.22303799999999]
1: (2) [-8.7848548, 115.323038]
2: (2) [-8.9848548, 115.52303799999999]
3: (2) [-8.8848548, 115.42303799999999]

How do I then iterate through these and map a latitude and longitude value to a component. I was trying like this:

<ReactMapGL>
    { mapRefs && mapRefs.map(coord => (
        <Marker latitude={coord[0]} longitude={coord[1]}>
            <div>
                ...
            </div>
        </Marker>
    ))}
</ReactMapGL>

This isn't working. What would be the correct way to do this, please?

You need use state values to render the UI elements and mapRefs is not available outside useEffect .

try like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM