我有一个名为 currentLocation 的变量,它是我从 navigator.geolocation.getCurrentPosition() 方法获取的对象。
{"timestamp":1575687610918,"mocked":false,"coords":{"altitude":0,"heading":0,"longitude":72.9815203,"latitude":19.2076923,"speed":0,"accuracy":35.90299987792969}}
我的问题是如何使用 map 在 React Native 应用程序中渲染它?我收到错误:未定义不是对象(评估“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 (
)
}
}
最佳答案
您想要循环对象并将数据显示为文本。您可以使用 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)
关于javascript - React Native 使用 map 渲染对象 : undefined is not an object (evaluating 'currentLocation.coords' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59222754/