简体   繁体   中英

Warning: Each child should have a unique key - Passing Array In ReactJS

I was practicing ReactJS tuts on Scrimba where you have to pass id props in array

 import React from 'react'; import Joke from './components/Joke.js' import jokesData from './components/jokesData'; function App() { const jokeComponents = jokesData.map(function(joke) { return ( <Joke obj={{key: joke.id, question: joke.question, punchline: joke.punchLine}} /> ) }) return ( <div> {jokeComponents} </div> ) } export default App;

Then I got a warning in console:

Warning log

警告日志

In the image above the key value was passed but I still got the warning message. I'm trying to pass the elements into a single object. Can anyone help me find the problem here?

You can add key attribute and pass in that joke.id .

  const jokeComponents = jokesData.map(function(joke) {
    return (
      <Joke 
        obj={{key: joke.id, question: joke.question, punchline: joke.punchLine}}
        key={joke.id)
      />
    )
  })

You have to pass key as prop to Joke component. id would be great choice because of how react reconciliation work.

<Joke  key={joke.id}
            obj={{key: joke.id, question: joke.question, punchline: joke.punchLine}} 
          />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM