第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 React 中為同一列表但不同的元素獲取不同的鍵?

如何在 React 中為同一列表但不同的元素獲取不同的鍵?

蝴蝶刀刀 2022-08-27 14:12:18
我從 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的組件,它將呈現(xiàn)在兩個不同的列中,并且將僅顯示該列的正確列(loc:右表示右側(cè)列,左側(cè)為左側(cè))    <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>我遇到的問題是我得到重復(fù)的鍵,因為是相同的組件和相同的邏輯。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 /></>錯誤:我做錯了什么嗎?這被認為是不好的嗎?這些是我在這里飛行的第一個小時。
查看完整描述

1 回答

?
慕田峪4524236

TA貢獻1875條經(jīng)驗 獲得超5個贊

你需要給容器一個 prop,而且你已經(jīng)有一個唯一的 id,所以你應(yīng)該使用它:keynoticia.id


const noticiaGenerator = (noticia) => (

  <div key={noticia.id}>

    <Card>

      ...

    </Card>

    <br />

  </div>

);

詳細了解為什么需要密鑰 。


它說:


當子項有鍵時,React 使用鍵將原始樹中的子項與后續(xù)樹中的子項進行匹配。


在您的示例中:


const noticiaGenerator = (noticia, key) => (

  // v this is the child that  should have the key.

  <React.Fragment>

    // v useless key

    <Card key={key}></Card>

    <br />

  </React.Fragment>

);


查看完整回答
反對 回復(fù) 2022-08-27
  • 1 回答
  • 0 關(guān)注
  • 96 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號