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

 

posted @ 2019-08-22 20:45  大笛子  阅读(2691)  评论(0编辑  收藏  举报