Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

reactjs - React: Siblings in a list must have unique key. Do the children of these list siblings need them too?

I am generating a series of divs by using .map() on my state (created via the useState() React hook).

Each of these divs has a unique React key. However, I still receive the following error:

Warning: Each child in a list should have a unique "key" prop.

Each of these <div> siblings has 30-50 children. Does each of those children need a unique React key as well?


The React documentation (https://reactjs.org/docs/lists-and-keys.html) appears ambiguous on this point.

It indicates that:

  • "A good rule of thumb is that elements inside the map() call need keys." (All elements? Or just the parent siblings?)

  • Keys must only be unique among siblings. (The scenario I describe follows this rule)

However none of its examples provide clarity on list siblings with many nested elements within.

Thanks in advance for your help.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

every time when you are rendering any series of nodes(React.Fragment, div, span etc) in loop like bellow you must have to do:

const list = [...list of your raw items]; // Array<{id: number, name: string}>

return (
  <main>
    {list.map((item, index) => (
      <section key={item.id}>
        <div><span>{item.name}</span></div>
      </div>
    ))}
  </div>
)
  1. define key for top-level node element inside map callback(in my example it is section);
  2. key should be an uniq parameter within current loop, it can be index but it is not recommended(for better performance in case if you dynamically modify list). Usually it is an ID of each entity;

ps. You do not have to pass down key for any children(in my example - div and span), but it is not harmful tho(just useless).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...