簡體   English   中英

我如何在React Native中解決uniqe關鍵道具問題

[英]How can i solve uniqe key prop problem in React native

我有React Native項目,當我嘗試構建手機時,出現此錯誤消息。 警告:數組或迭代器中的每個子代都應具有唯一的“鍵”道具。 但是它可以在計算機模擬器上運行。

模擬器 電話

這是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>
    );
  }
}

最簡單的解決方案是更新keyExtractor,因為它似乎不起作用。 它看起來不像您的數據具有id屬性,但確實具有matchId屬性。 這意味着您可以執行以下操作。

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

或者,您可以使用索引作為關鍵字並執行此操作

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM