react-native報錯Encountered two children with the same key, `%s`.


問題

 

 

 

解決

如圖所知是因為key的關系,我們在使用FlatList時導致的這個錯誤,官網上FlatList中的key有如下說法,“非必須”,“不設置默認key/index”.實際上在使用class時使用FlatList,會在flat內部會給我們指定好key,我們不用去寫key.!但是在hook寫法中key我們需要人為設定,並且必須把key設置為string類型

 

 

 修改后的代碼

import React ,{useEffect,useState} from 'react';
import { StyleSheet, Text, View ,Image,FlatList} from 'react-native';

export default function App() {
  
  let [result,setResult]=useState([]) 
  useEffect(() => {
    fetch('.....')
    .then((response)=>response.json())
    .then((resJson)=>{
      result=result.concat(resJson)
      setResult(result)
    })
  })
  const renderMovie=({item})=>{
    return(      
      <View>
     //replace可以替換img的url中的內容 <Image source={{uri:item.img.replace('w.h','100.100')}} style={styles.imgS}></Image> </View> ) } return ( <View style={styles.container}> <Text></Text>
    //重點!!!toString方法和keyExtractor <FlatList data={result} renderItem={renderMovie} keyExtractor={(item,index)=>index.toString()}> </FlatList> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'center', }, imgS:{ width:100, height:150 } });

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM