React Native:uri在平面列表中多次呈现

React Native : uri rendered multiple times in flatlist

我是 React Native 的新手。我尝试向我的应用程序添加平面列表。 我有一组这样设计的数据:

   ["https://hi.com//image.png",  //uri
    "hello",
    "https://hi.com//image2.png",
    "welcome",      
    "https://hi.com//image3.png",
    "great",      
      ../..
   ]

问题是我的图片显示了,但右侧的文本实际上是我的 uri 字符串化。

我认为 keyExtractor 有问题:

renderItem =({item}) => {           
return(    
  <View style ={{flex:1, flexDirection:'row'}}>
    <Image source ={{uri: item}}/>
    <View style ={{flex:1, justifyContent: 'center'}}>
      <Text>{item}</Text>
    </View>
  </View>
  )
}

render() {  
return (
  <View style={styles.mainContainer}>
      <FlatList 
        data= {this.state.dataSource}              
        keyExtractor={(item,index) => index.toString()}
        renderItem= {this.renderItem}
        /> 
  </View>       
  );
}

您的 renderItem 函数遍历数组的每个元素,不确定它是您数据类型的最佳选择,也许尝试使用类似这样的方法

const data = [{uri: 'https://link.io', text: 'hello'},{uri: 'http://anotherlink.co', text: 'bye'}]

然后在您的 renderItem 函数中传递数据:

    <Image source ={{uri: item.uri}}/>
    <Text>{item.text}</Text>

另一方面,如果您需要保留平面数组,也许可以编写一些函数,将索引除以 2挑战 ;) 祝你好运,希望对你有所帮助

你的平面列表渲染项目每次循环时都试图访问 loop.so 中的项目,你正在将项目传递给 Image 并将项目传递给 Text.As @wijuwiju 建议,这是最好的方法实施 it.try 以维护 data.Then 的密钥,您的平面列表将正确呈现。

像这样存储项目:

 profilePicture: 'https://picsum.photos/200',

像这样设置图像源:

<Image source={{uri:profilePicture}}/>