[英]Uncaught TypeError: Cannot read property 'map' of undefined ( REACT NATIVE - Javascript )
Been trying to import a Json file and then explore and display it in a React Native app.一直在尝试导入一个 Json 文件,然后在 React Native 应用程序中探索和显示它。 I am just learning React Native, and at the same time Javascript.我只是在学习 React Native,同时也在学习 Javascript。
import React, { Component } from 'react';
import {
Text,
View,
AsyncStorage
} from 'react-native';
import{eventos} from './Events';
export default class Admin extends React.Component{
constructor(props){
super(props);
this.state={
eventos
}
try{
AsyncStorage.getItem(eventos).then((value)=>{
if(value!=null){
console.log("Events esta completo")
}else{
console.log("Events esta vacio")
}
this.setState({
eventos:JSON.parse(value)
})
})
}catch(err){
console.log(err)
}
}
parseEventsData(){
console.log("Deberia salir algo")
return this.state.events.map((eventos,i)=>{
return(
<View key={i}>
<Text>
{eventos.title}
</Text>
<Text>
{eventos.responsible}
</Text>
<Text>
{eventos.description}
</Text>
</View>
)
})
}
render(){
return(
<View>
{this.parseEventsData()}
<Text>No salio nada</Text>
</View>
);
}
} }
The Json is next.接下来是 Json。
enter image description here在此处输入图片说明
And this is the error I get.这是我得到的错误。
enter image description here在此处输入图片说明
I am just learning React Native, and at the same time Javascript.我只是在学习 React Native,同时也在学习 Javascript。
Checking your code, you can notice that the state var is called "eventos" and you are mapping through "this.state.events".检查您的代码,您会注意到状态变量称为“eventos”,并且您正在通过“this.state.events”进行映射。 Just a typo.只是一个错字。
You have a couple of issues:你有几个问题:
parseEventsData
.您的parseEventsData
似乎有拼写错误。 Everywhere else you call it eventos
, but here you call it events
.在其他任何地方都称为eventos
,但在这里称为events
。 Not sure which you intend, but the mismatch means that your call to setState
is setting a different property than you reference later on in parseEventsData
.不确定您打算使用哪个,但不匹配意味着您对setState
的调用设置的属性与您稍后在parseEventsData
引用的属性不同。this.state.eventos
will be undefined at first, and won't be defined until your promise in the constructor resolves.假设您修复了上面的错字, this.state.eventos
将是未定义的,并且直到您在构造函数中的承诺解决时才会被定义。 When you call this.state.eventos.map
, you are calling map on a value that is undefined as your error indicates.当您调用this.state.eventos.map
,您是在一个未定义的值上调用 map ,正如您的错误所指示的那样。 You need to either check whether it is undefined before calling map
, or you should initialize it to an empty array.您需要在调用map
之前检查它是否未定义,或者您应该将其初始化为空数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.