【发布时间】:2022-01-05 08:04:58
【问题描述】:
花了 4 个多小时解决了这个问题,但没有成功。我最近开始学习如何使用 react 和 javascript 编写代码来创建一个允许用户将他们喜欢的位置添加到列表中的应用程序。
我能够连接到 firestore 并将数据返回到某个状态,但由于某种原因,我无法在“render()”和“return()”中访问它。我的控制台记录了经度和纬度等值,但是当我通过它访问状态时不起作用。这是代码,请看下面的照片
state = {
regionSet: false,
}
componentDidMount() {
Geolocation.getCurrentPosition(position => {
const { latitude, longitude } = position.coords
const region = {
...this.state.region,
latitude,
longitude,
latitudeDelta: 0.008,
longitudeDelta: 0.008,
}
this.setState({ region, regionSet: true })
})
userData = async () => {
const user = auth().currentUser;
var userRef = firestore().collection('favoritelist').doc(user.uid).collection(user.uid);
const markers = [];
await firestore().collection('favoritelist').doc(user.uid).collection(user.uid).get()
.then(querySnapshot => {
querySnapshot.docs.forEach(doc => {
markers.push(doc.data());
});});
this.setState({markers});
console.log(this.state.markers)
console.log(this.state.markers[0].lat)
};
userData()
}
render() {
const { markers } = this.state
const user = auth().currentUser;
const mapRegion = {latitude: 37.782822, longitude: -122.4067605}
return (
<View>
{console.log(markers)}
<Text>
{this.state.markers[0].lat}
</Text>
</View>
console logs the data/state perfectly fine
state doesn't work in a text and return
如果可能的话,感谢您的阅读和帮助:)
【问题讨论】:
-
因为
markers[0].lat在您第一次渲染视图时不存在。检查markers[0].lat是否存在,然后有条件地渲染它。 -
对不起,我不太清楚你的意思(还是很新哈哈)。它可以在 render() 中使用 console.log (marker),但是当它是我不理解的 marker[0].lat 时不能
标签: javascript reactjs firebase react-native google-cloud-firestore