【问题标题】:React Native: Warning: Each child in a list should have a unique "key" propReact Native:警告:列表中的每个孩子都应该有一个唯一的“关键”道具
【发布时间】:2020-11-20 14:36:02
【问题描述】:

我是 React Native 的新手,有一个问题。

我收到此警告:列表中的每个孩子都应该有一个唯一的“关键”道具。

我什么都试过了。现在我什至将 Math.random() 作为键,但我仍然收到警告。

Home.js:

return(

    
  <ScrollView style={styles.container}>

<StatusBar barStyle='light-content' />


<ImageBackground source={image} style={styles.image} imageStyle={styles.image2}>
    <LinearGradient colors={['transparent', 'rgba(249,249,249,1)' ]} locations={[.4, 1]}
        style={{
          position: 'absolute',
          left: 0,
          right: 0,
          top: 0,
          height: 400
        }} />
    <TouchableOpacity activeOpacity={0.9} style={styles.topNews} onPress={()=> navigation.navigate('WebView')}>
      <Text style={styles.topCategoryText}>ITALIAN LEAGUE</Text>
      <Text style={styles.topTitleText}>Juventus legend: Ronaldo is natural to be criticized</Text>
      <Text style={styles.topSourceText}>CNN Sport</Text>
      </TouchableOpacity>

      
    
    </ImageBackground>

    <View style={{marginHorizontal: 10, flex: 1}}><RNMasonryScrollView 
            colums='2' 
            columnStyle={{flexDirection: 'column'}} 
            oddColumnStyle={{flex: 1, marginRight:15, marginLeft:10}}
            evenColumnStyle={{flex:1,marginLeft:15}}
            >
      {[
            <NewsDetail Key='1' title="Papers: Salah eager for Barca move" category='LA LIGA' imageSrc='https://en.as.com/en/imagenes/2020/06/11/football/1591881357_315795_noticia_normal.jpg'/>,
            <NewsDetail Key='2' title="Man Utd struggles 'mentally impacting' Pogba, says France boss Deschamps" category='PREMIER LEAGUE' imageSrc='https://resources.premierleague.com/premierleague/photo/2019/06/20/88784d96-ef4b-4414-8b59-517c15b162a5/MW1-EditorialLead-new.png'/>,
            <NewsDetail Key='3' title="Arsenal's complete player: The meteoric rise of Vivianne Miedema" category='PREMIER LEAGUE' imageSrc='https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTupBTx2is9w3Z7pIhrorpPDMTFHmQhS1Ypmg&usqp=CAU'/>,
            <NewsDetail Key='4' title="Mourinho hit with suspension by UEFA" category='SERIE A' imageSrc='https://www.telegraph.co.uk/content/dam/football/2018/02/13/TELEMMGLPICT000153853426_trans_NvBQzQNjv4BqwD2sfO9joeQ6RY-qlTATNB2cSHopZMn-aCc647VHTAY.jpeg'/>,
            <NewsDetail Key='5' title="'Ronaldo is definitely faster than me!' – Bolt" category='LA LIGA' imageSrc='https://resources.premierleague.com/premierleague/photo/2018/08/10/bf1acdf0-7b10-4dfe-8844-06f0f18d5c38/2018-08-10T192712Z_1257041591_RC18CE142CA0_RTRMADP_3_SOCCER-ENGLAND-MUN-LEI.JPG'/>,
            <NewsDetail Key='6' title="Southgate admits to fears over Maguire's career" category='LIGUE 1' imageSrc='https://images.daznservices.com/di/library/GOAL/a8/c9/vivianne-miedema-goal-50-gfx_nuhcgkr4tthu1kyux2ymq4y4l.jpg?t=-1147520971&amp;quality=60&amp;w=1200'/>,
            ]}
    </RNMasonryScrollView></View>

  </ScrollView>
  

  )

NewsDetail.js

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





const NewsDetail = (props) => {

    const random = Math.random()
    const ViewWidth = 157.5
    // const [imageSize, setImageSize] = useState({width: 0, height: 0});
    // const [viewSize, setViewSize] = useState({width: 0, height: 0});
    const [imageHeight, setHeight] = useState(0);

    const myUri = props.imageSrc;

    useEffect(() => {
        Image.getSize(myUri, (width, height) => {
        
            setHeight(height / (width / ViewWidth));
            
            
        
        });

    }, []) 

    if(imageHeight > 0){

        console.log(random)
        

        return (
            <View style={styles.newsDetail} key={`${random}`}>
                <Image
                resizeMode='cover'
                    style={{
                        width: ViewWidth, 
                        height: imageHeight, 
                        borderTopLeftRadius: 7, 
                        borderTopRightRadius: 7,
                        }} 
                    source={{ uri: myUri,}}
                />
                <Text style={styles.textOne}>{props.category}</Text>
                <Text style={styles.textTwo}>{props.title}</Text>
    
            </View>)

    } else return null;

    
      
    
    

}

const styles = StyleSheet.create({


    image:{
        
        width: '100%',
        borderTopLeftRadius: 7, 
        borderTopRightRadius: 7

    },
    newsDetail:{

         
        backgroundColor: "white",
        marginTop: 10,
        borderRadius: 7,
        opacity: 0.9,
    shadowColor: "grey",
    shadowRadius: 5,
    shadowOffset: {width: 0, height: 0},
    shadowOpacity: 0.3
        

    },
    textOne:{
        fontSize: 10,
        color: '#7A7F82',
        fontWeight: 'bold',
        paddingTop: 10,
        paddingHorizontal: 10,
        paddingBottom:3
    },
    textTwo:{
        fontSize: 14,
        color: '#2D3041',
        fontWeight: 'bold',
        paddingHorizontal: 10,
        paddingBottom:10
    }


});

export default NewsDetail;

我不知道该怎么办。有什么帮助吗?另外,是否有任何网站可以让我付费获得有关 React Native 的问题的快速帮助?与 StackOverflow 类似,您只需付费即可快速获得所有问题的答案?

【问题讨论】:

  • 如果您能提供我们可以帮助您的代码,您可以在这里很快得到答案。
  • 尝试从代码中删除key={}
  • 属性是key而不是Key(注意小写字母)。你试过了吗?

标签: react-native


【解决方案1】:

生成列表的正确方法是创建一个对象数组,然后使用地图显示。在您的代码中,它几乎是正确的。您应该使用 key 而不是 Key。

const articles = [ 
{ id: 1, title: "Papers: Salah eager for Barca move", category: 'LA LIGA', imageSrc: 'https://en.as.com/en/imagenes/2020/06/11/football/1591881357_315795_noticia_normal.jpg' },
{id: '2', title: "Man Utd struggles 'mentally impacting' Pogba, says France boss Deschamps", category: 'PREMIER LEAGUE', imageSrc: 'https://resources.premierleague.com/premierleague/photo/2019/06/20/88784d96-ef4b-4414-8b59-517c15b162a5/MW1-EditorialLead-new.png'},
{ id:'3',title: "Arsenal's complete player: The meteoric rise of Vivianne Miedema", category: 'PREMIER LEAGUE', imageSrc: 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTupBTx2is9w3Z7pIhrorpPDMTFHmQhS1Ypmg&usqp=CAU'}]

<RNMasonryScrollView 
            colums='2' 
            columnStyle={{flexDirection: 'column'}} 
            oddColumnStyle={{flex: 1, marginRight:15, marginLeft:10}}
            evenColumnStyle={{flex:1,marginLeft:15}}
            >
      { articles.map((article) => {
          return <NewsDetail key={article.id} title={article.title} imageSrc={article.imageSrc} />
       })}
           
    </RNMasonryScrollView>

【讨论】:

  • 谢谢!我以为我必须在 NewsDetail 中使用 key 属性,这就是为什么我使用“Key”作为道具来发送它。你学得越多。
  • 关键是要防止那些项目每次都被重新渲染,所以它必须是唯一的并且是固定的。渲染时不能是 Math.random()。
猜你喜欢
  • 1970-01-01
  • 2021-11-18
  • 2020-03-01
  • 2019-08-04
  • 2021-01-12
  • 2022-06-28
  • 1970-01-01
  • 2023-02-17
  • 2019-12-05
相关资源
最近更新 更多