reactjs - 重复的 JSON 数据 - React Native
问题描述
谁能向我解释为什么我的数据和标题一遍又一遍地重复,我该如何解决这个问题?
我还有一条黄色错误消息,我认为它可能与此有关,上面写着“警告:列表中的每个孩子都应该有一个唯一的“关键”道具。”
这可能是一些基本的东西,但我是新来的,可以从这里的人们那里做出反应和学习很多东西,并感谢您的帮助!
谢谢
import React from "react";
import { StyleSheet, FlatList, Text, View } from "react-native";
import styled from "styled-components";
export default class FetchExample extends React.Component {
static navigationOptions = {
header: null
};
constructor(props) {
super(props);
this.state = { isLoading: true };
}
componentDidMount() {
const localMovieData = require("../assets/test.json");
this.setState(
{
isLoading: false,
dataSource: localMovieData.movies
},
function() {}
);
}
_renderItem = info => {
return (
<View>
<Title style={styles.title}> Contact Information </Title>
{this.state.dataSource.map((movie, index) => (
<Text style={styles.text}>
{movie.name} - {movie.contact}
</Text>
))}
</View>
);
};
render() {
return (
<View style={styles.container}>
<FlatList
data={this.state.dataSource}
renderItem={this._renderItem}
keyExtractor={({ id }, index) => id}
/>
</View>
);
}
}
const Title = styled.Text`
font-size= 16px;
color: #b8bece;
font-weight: 500;
`;
const styles = StyleSheet.create({
container: {
paddingVertical: 50,
backgroundColor: "#f0f3f5"
},
text: {
fontSize: 15,
color: "#008000",
padding: 10
},
image: {
width: 45,
height: 45,
borderRadius: 20,
marginLeft: 20
},
title: {
fontSize: 16,
color: "black"
}
});
JSON数据
{
"title": "The Basics - Networking",
"description": "Your app fetched this from a remote endpoint!",
"movies": [
{ "id": "1", "name": "Tim ", "contact": "xxx@ymail.com" },
{ "id": "2", "name": "Bradley", "contact": "xxx@ymail.com" },
{ "id": "3", "name": "James", "contact": "outlook.com" },
{ "id": "4", "name": "Elle", "contact": "hotmail" },
{ "id": "5", "name": "Bob", "contact": "yahoo" }
]
}
解决方案
问题在于您的“renderItem”方法
当 FlatList 组件接收到数据时,它会自动将其分离为对象,并将每个对象发送到“renderItem”方法
所以你需要做的是:在渲染函数中获取每个项目的 item 属性并将其发送到 _renderItem
删除每个 renderItem 内的映射并访问新项目,如下所示:
_renderItem = item => {
return (
<View>
<Text style={styles.title}> Contact Information </Text>
<Text>
{item.name} - {item.contact}
</Text>
</View>
);
};
render() {
return (
<View style={styles.container}>
<FlatList
data={this.state.dataSource}
renderItem={(item)=>this._renderItem(item.item)}
keyExtractor={(item, index) => {return item.id;}}
/>
</View>
);
}
至于关键警告:
您需要像这样返回密钥
keyExtractor={(item, index) => {
return item.id;
}}
你可以在这里看到一个工作代码
推荐阅读
- json - React 本机日志将对象显示为“[object Object]”
- sql-server - 是否可以在单个 SQL Server 查询中产生幻读?
- .net - 阅读 Telerik 电子表格
- c# - 如何在 C# Wpf MVVM 中基于文本块中的特殊字符拆分字符串后使用内联
- testing - 在TestNG自动化中将另一个类的一个方法的依赖项调用到另一个类时出错
- python-3.x - Python:如何在保留目录结构的同时将文件从远程机器复制到本地?
- python-3.x - Python dict 序列化:从“相同”的 dict 中获得不同的结果
- python - Pickle 文件在一台机器上工作,在另一台机器上打开时不起作用
- angular - 角度 - 如何将内容与卡片的中心对齐
- ruby-on-rails - 在 Rails 5 应用程序中找不到应用程序 javascript 文件