【问题标题】:How to loop through and return the values of a javascript object?如何循环并返回 javascript 对象的值?
【发布时间】:2020-11-01 08:37:07
【问题描述】:

(抱歉,如果我的某些术语不正确)

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

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

【问题讨论】:

  • “不工作”以什么方式?你有错误吗?数据错误?还有什么?
  • 嗨,伙计,啊,对不起,我错过了那一点。它没有输出任何东西,可能是由于 'mapRefs &&' 条件的事情。

标签: javascript reactjs firebase google-cloud-firestore react-map-gl


【解决方案1】:

您需要使用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>
)

【讨论】:

  • 您好,Naren,感谢您的帮助。我收到“res.map 不是函数”错误。
  • 那它是如何工作的呢? `res.forEach(data => { mapRefs.push([data.data().myLatitude, data.data().myLongitude]); });``
  • 改变了你的逻辑,现在检查!
  • 超级我的朋友,你绝对是明星⭐(我想我也明白了。)谢谢你,祝你有美好的一天!
  • 很高兴为您提供帮助,也祝您有愉快的一天!
猜你喜欢
  • 2022-11-01
  • 2016-10-24
  • 1970-01-01
  • 2021-07-16
  • 2016-05-29
  • 2012-01-03
  • 2014-01-11
  • 1970-01-01
相关资源
最近更新 更多