【问题标题】:How can i solve uniqe key prop problem in React native我如何解决 React Native 中的唯一键道具问题
【发布时间】:2019-05-22 12:12:39
【问题描述】:

我有 React Native 项目,当我尝试构建我的手机时,我收到了这个错误消息。 警告:数组或迭代器中的每个子元素都应该有一个唯一的“key”属性。但它适用于计算机模拟器。

这里是json数据:http://hazir.net/api/match/today

这是我的代码,

import React from 'react';
import { FlatList, ActivityIndicator, Text, View  } from 'react-native';

export default class Matches extends React.Component {

  constructor(props){
    super(props);
    this.state ={ isLoading: true}
  }

  componentDidMount(){
    return fetch('http://hazir.net/api/match/today')
      .then((response) => response.json())
      .then((responseJson) => {

        this.setState({
          isLoading: false,
          dataSource: responseJson,
        }, function(){

        });

      })
      .catch((error) =>{
        console.error(error);
      });
  }



  render(){

    if(this.state.isLoading){
      return(
        <View style={{flex: 1, padding: 20}}>
          <ActivityIndicator/>
        </View>
      )
    }

    return(
      <View style={{flex: 1, paddingTop:20}}>
        <FlatList
          data={this.state.dataSource}
          renderItem={({item}) => <Text>{item.matchId}, {item.matchDate}</Text>}
          keyExtractor={({id}, index) => id}
        />
      </View>
    );
  }
}

【问题讨论】:

标签: json reactjs react-native networking


【解决方案1】:

最简单的解决方案是更新您的 keyExtractor,因为它似乎无法正常工作。看起来您的数据没有 id 属性,但它确实有 matchId 属性。这意味着您可以执行以下操作。

<FlatList
 ...
 keyExtractor={({matchId}, index) => matchId.toString()}
/> 

或者,您可以使用索引作为键并执行此操作

<FlatList
 ...
 keyExtractor={({matchId}, index) => index.toString()}
/> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 2020-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-01
    相关资源
    最近更新 更多