如何在 React 中为同一列表但不同的元素获取不同的键?

我从 React 开始(5 天前),所以很抱歉,如果这是一个基本问题,或者我可能没有正确地制定这个。


我有一个包含此格式的 JSON。


[{

    "id":"1",

    "header": "Ultimo Momento",

    "titulo": "Alerta Mundial",

    "texto": "Aliens nos atacan sin piedad.",

    "tipo": "Info",

    "loc": "left"

},

{

    "id":"2",

    "header": "Info",

    "titulo": "Vuelve el Futbol",

    "texto": "Aliens nos atacan sin piedad.",

    "tipo": "Light",

    "loc": "left"

},

{

    "id":"3",

    "header": "Info",

    "titulo": "Alerta Mundial",

    "texto": "Aliens nos atacan sin piedad.",

    "tipo": "Dark",

    "loc": "right"

}]

我有一个名为Noticias的组件,它将呈现在两个不同的列中,并且将仅显示该列的正确列(loc:右表示右侧列,左侧为左侧)


    <MDBCol md="3" className="d-flex align-items-center flex-column">

      <Noticias Noticias={NoticiasData} Location={"left"} />

    </MDBCol >



    <MDBCol  md="6" className="d-flex align-items-center flex-column">

      <Salas Salas={SalasData} />

    </MDBCol >



    <MDBCol  md="3" className="d-flex align-items-center flex-column">

      <Noticias Noticias={NoticiasData} Location={"right"} />

    </MDBCol >


  </MDBRow>

我遇到的问题是我得到重复的键,因为是相同的组件和相同的逻辑。


class Noticias extends Component {

state = {}


render() {

    const {


        Noticias,

        Location


    } = this.props;



    return (

        Noticias.filter((noticia) => noticia.loc === Location).map((noticia, idx) =>

            (

                noticiaGenerator(noticia, idx)

            ))

    )

}

}


NoticiaGenerator看起来像这样:


const noticiaGenerator = (noticia, key) =>

<>

    <Card

        bg={noticia.tipo.toLowerCase()}

        key={key}

        id={noticia.id}

        text={noticia.tipo.toLowerCase() === 'light' ? 'dark' : 'white'}

        style={{ width: '18rem' }}

    >

        <Card.Header>{noticia.header}</Card.Header>

        <Card.Body>

            <Card.Title>{noticia.titulo}</Card.Title>

            <Card.Text>{noticia.texto}</Card.Text>

        </Card.Body>

    </Card>

    <br />

</>

错误:

http://img2.mukewang.com/6309b5f10001be1808840293.jpg

我做错了什么吗?这被认为是不好的吗?这些是我在这里飞行的第一个小时。


蝴蝶刀刀
浏览 81回答 1
1回答

慕田峪4524236

你需要给容器一个 prop,而且你已经有一个唯一的 id,所以你应该使用它:keynoticia.idconst noticiaGenerator = (noticia) => (&nbsp; <div key={noticia.id}>&nbsp; &nbsp; <Card>&nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; </Card>&nbsp; &nbsp; <br />&nbsp; </div>);详细了解为什么需要密钥 。它说:当子项有键时,React 使用键将原始树中的子项与后续树中的子项进行匹配。在您的示例中:const noticiaGenerator = (noticia, key) => (&nbsp; // v this is the child that&nbsp; should have the key.&nbsp; <React.Fragment>&nbsp; &nbsp; // v useless key&nbsp; &nbsp; <Card key={key}></Card>&nbsp; &nbsp; <br />&nbsp; </React.Fragment>);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript