我有一个名为currentLocation的变量,它是从navigator.geolocation.getCurrentPosition()方法中获得的一个对象。
{"timestamp":1575687610918,"mocked":false,"coords":{"altitude":0,"heading":0,"longitude":72.9815203,"latitude":19.2076923,"speed":0,"accuracy":35.90299987792969}}我的问题是,如何在一个使用地图的本地应用程序中呈现它呢?我得到了一个错误:未定义不是一个对象(计算'currentLocation.coords')。我想要能够映射到这个对象,并简单地显示数据为文本!我是新的反应本地人,所以任何帮助都会非常感谢。谢谢!
以下是守则:
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 (
)
}
}发布于 2019-12-07 03:56:07
您希望在对象上循环并显示数据,因为text.You可以为此使用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)发布于 2019-12-07 03:43:13
您可能正在寻找像这个https://github.com/react-native-community/react-native-maps这样的包。您可以使用MapView组件在您的react本地应用程序上呈现地图,并使用标记组件来锁定当前位置。我觉得这些文件能帮你。
发布于 2019-12-07 05:07:21
如果它是对象
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>
);
}
}https://stackoverflow.com/questions/59222754
复制相似问题