javascript - React Native 使用 map 渲染对象 : undefined is not an object (evaluating 'currentLocation.coords' )

标签 javascript reactjs react-native

我有一个名为 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/

相关文章:

javascript - 修改函数参数

javascript - Javascript 中 reduce 方法的奇怪行为

javascript - typescript 对象奇怪的类型语法

reactjs - React-sortable-hoc——在没有实验类属性的情况下维护新的排序顺序

javascript - 在 react 中更改状态时不会重新渲染组件

react-native - React native BottomTabNavigator with DrawerNavigator,如何保持底部导航器一直可见

javascript - 正确使用 Promises 和 Await/Async

javascript - 使用 redux-thunk 时操作必须是普通对象

javascript - 如何在 React Native 的 <Text> JSX 标签中渲染字符串中的变量

javascript - React-Native DatePickerIOS minimumDate Prop