首页 > 解决方案 > 重复的 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" }
  ]
}

标签: reactjsreact-nativereact-native-android

解决方案


问题在于您的“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;
    }}

你可以在这里看到一个工作代码


推荐阅读