我有一个名为currentLocation的变量,这是我从navigator.geolocation.getCurrentPosition()方法获得的对象。
{"timestamp":1575687610918,"mocked":false,"coords":{"altitude":0,"heading":0,"longitude":72.9815203,"latitude":19.2076923,"speed":0,"accuracy":35.90299987792969}}
我的问题是如何使用地图在React Native应用中渲染它?我收到错误消息:undefined不是对象(正在评估'currentLocation.coords')。我希望能够映射到该对象,并简单地将数据显示为文本!我是React Native的新手,所以我们将不胜感激。谢谢!
以下是代码:
export default class HomeScreen extends React.Component {
constructor(props) {
super(props)
this.state =
{
currentLocation : '',
}
}
async componentDidMount() {
var location
setInterval(() => {
navigator.geolocation.getCurrentPosition(
position => {
location = JSON.stringify(position)
//console.log(location)
this.setState({ location })
},
error => Alert.alert(error.message),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
);
this.setState({ currentLocation : location })
}, 1000)
}
render() {
var { currentLocation } = this.state
if(typeof(currentLocation) != undefined)
console.log('Inside render =========> ', currentLocation.coords)
return (
)
}
}
答案 0 :(得分:1)
您要遍历对象并将数据显示为文本。您可以使用Object.keys()
。
这是操作方法-
const p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Object.keys(p).map((i) => {
console.log(i, p[i]) // i will be the key of object and p[i] will be the value of
key//
//return jsx using the above logic//
})
您可以在此处查看其他方法来遍历对象-How do I loop through or enumerate a JavaScript object?
希望这对您有所帮助。
编辑:- 该错误是因为您的状态不是对象。这是一个字符串,因为您这样做
location = JSON.stringify(position)
您可以删除此字符串化,也可以在内部渲染中删除
const currentLocation = JSON.parse(this.state.currentLocation)
答案 1 :(得分:0)
您可能正在寻找像这样的https://github.com/react-native-community/react-native-maps软件包。 您可以使用MapView组件在本机应用程序上渲染地图,并使用Marker组件固定当前位置。我认为文档可以为您提供帮助。
答案 2 :(得分:0)
如果是对象
import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
let obj = {"timestamp":1575687610918,"mocked":false,
"coords":{"altitude":0,"heading":0,"longitude":72.9815203,
"latitude":19.2076923,"speed":0,"accuracy":35.90299987792969
}}
export default class App extends React.Component {
render() {
const {timestamp, coords } = obj;
return (
<View>
<Text>{timestamp}</Text>
<Text>{coords.latitude}</Text>
<Text>{coords.longitude}</Text>
</View>
);
}
}
如果是对象数组
let arr = [{"timestamp":1575687610918,"mocked":false,
"coords":{"altitude":0,"heading":0,"longitude":72.9815203,
"latitude":19.2076923,"speed":0,"accuracy":35.90299987792969
}}]
export default class App extends React.Component {
render() {
return (
<View>
{arr && arr.map(a=>
<View key={Math.random()*10000}>
<Text>{a.timestamp}</Text>
<Text>{a.coords.latitude}</Text>
<Text>{a.coords.longitude}</Text>
</View>
)}
</View>
);
}
}