我目前正在学习RN,现在我正在尝试动态显示我在本地创建的JSON文件中的数据。我想做的是显示字符列表,并为用户提供按特定字符按钮将其带到其个人资料屏幕的机会。但是,我不断收到一条消息,提示“无法将未定义或null转换为对象”。有人可以向我解释为什么我得到那个吗?我该如何解决?任何帮助或线索都将受到赞赏。
这是我创建的JSON文件:
//Characters.js
const characters = [
{ id: "1", name: "Homer Simpson", occupation: "Nuclear Safety Inspector" },
{ id: "2", name: "Marge Simpson", occupation: "Stay-at-home mom" },
{ id: "3", name: "Bart Simpson", occupation: "Student" },
{ id: "4", name: "Lisa Simpson", occupation: "Student" },
{ id: "5", name: "Maggie Simpson", occupation: "Baby" },
{ id: "6", name: "Barney Gumble", occupation: "Homer's BFF" },
{ id: "7", name: "Kent Brockman", occupation: "TV Anchor" },
{ id: "8", name: "Mr. Burns", occupation: "Nuclear Plant Owner" },
{ id: "9", name: "Ralph Wiggum", occupation: "Police Officer" },
{ id: "10", name: "Otto Mann", occupation: "School Bus Driver" },
{ id: "11", name: "Santa's Little Helper", occupation: "Family Pet" },
{ id: "12", name: "Scratchy", occupation: "Cat" }
];
export default characters;
这就是我尝试将其引入的方式:
import React, { Component } from "react";
import { Text, View } from "react-native";
import { withNavigation } from "react-navigation";
import {
createStackNavigator,
createAppContainer,
createBottomTabNavigator
} from "react-navigation";
import characters from "../Data/Characters";
class CharacterDirectory extends React.Component {
static navigationOptions = {
title: "The Simpsons",
headerStyle: {
backgroundColor: "#53b4e6"
},
headerTintColor: "#f6c945",
headerTitleStyle: {
fontWeight: "bold"
},
};
render() {
const { navigation } = this.props;
const type = navigation.getParam('type');
const typeData = characters[type];
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
{Object.keys(typeData).map(id => (
<Button
title={'Go to${typeData[id].name}'}
onPress={() =>
this.props.navigation.push('Details', {
type,
item: typeData[id],
})}
/>
))}
</View>
)
}
}
export default CharacterDirectory;
答案 0 :(得分:1)
可以直接使用。尝试使用此方法。
#include *
答案 1 :(得分:0)
这里可能有些困惑
{Object.keys(typeData).map(id => (
<Button
title={'Go to${typeData[id].name}'}
onPress={() =>
this.props.navigation.push('Details', {
type,
item: typeData[id],
})}
/>
))}
使用此代码const typeData = characters[type];
。 Typedata可能等于{ id: "1", name: "Homer Simpson", occupation: "Nuclear Safety Inspector" }
。如果循环遍历此对象的键。 id等于这些id
,name
,occupation
中的一个,如果只想为一个Typedata显示1个按钮,则它将不正确。