简体   繁体   中英

Each child in a list should have a unique "key" prop. I made it, but still see this error

I know about key prop, so i made it in listitem component

const ListItem = ({item}) => {
const {result, time, id} = item;
return(
    <li key={id} className='list__item'>
        <span className='item__result'>{result} cps</span>
        <span className='item__date'>{time}</span>
        <button className='item__delete'>delete</button>
    </li>
)}

And here is component, where I use it

const Leadboard = () => {
const [data, setData] = useState([{result:'5,63', time:'08.06.2022', id:  (new Date()).toString(16)}, {result:'5,63', time:'08.06.2022', id: +(new Date() - 1)}, {result:'5,63', time:'08.06.2022', id: +(new Date() - 2)}]);

let elements=data.map(item => {
    return (
        <>
            <ListItem item={item} />
        </>
    )
});

return(
    <div className='app-leadboard'>
        <span className='app-leadboard__title'>Your's best results:</span>
        <ol className='app-leadboard__list' type='1'>
            {elements}
        </ol>
    </div>
)}

But after render I still see "key prop" error

I spent so much time on this, but can't understand what's wrong. So smb, help pls with it

You've got the wrong list. It's the <ListItem> components that need the key. (And you can get rid of the react fragments around them because they are pointless).

React first accesses the empty bracket ( <> </> ) before accessing the key attribute in your child component.

So you need to either

  1. Make use of the empty brackets and pass the key attribute to it
// Use React.Fragment 

  let elements=data.map(item => { return 
  (
   <React.Fragment key={item.id}>
 <ListItem item={item} />
</React.Fragment>
)
});

and remove the key in the child ( ListItem ) component

ListItem.js
 <li 
 /*  Remove this
key={id} 
*/

  className='list__item'>

OR

Get rid of the empty brackets ( <> </> ) and reference the child's component directly.

let elements=data.map(item => {
return (<ListItem item={item} />)
});

and leave the key attribute in the child component

More on React Fragment. React Official Docs

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