简体   繁体   中英

"react" Each child in a list should have a unique "key" prop

An error seems to occur because the key value is not entered in the map function, but I do not know how to modify the code.

The array is structured like this:

    const tabContArr=[
        {
            tabTitle:(
                <span className={activeIndex===0 ? "is-active" : ""} onClick={()=>tabClickHandler(0)}>0</span>
            ),
         
        },
        {
            tabTitle:(
                <span className={activeIndex===1 ? "is-active" : ""} onClick={()=>tabClickHandler(1)}>1</span>
            ),
           
        },
        {
            tabTitle:(
                <span className={activeIndex===2 ? "is-active" : ""} onClick={()=>tabClickHandler(2)}>2</span>
            ),
          
        },
        {
            tabTitle:(
                <span className={activeIndex===3 ? "is-active" : ""} onClick={()=>tabClickHandler(3)}>3</span>
            ),
           
        }
    ];

An error occurs in the map function part.

   {tabContArr.map((section)=>{
                return section.tabTitle
            })}

What you have done is not the right way. If you have data, instead of passing the ReactElement into the array you should pass it into the map function like this:

{tabContArr.map((tab, index)=>{
      return <span 
         className={activeIndex === index ? "is-active" : ""} 
         onClick={()=>tabClickHandler(index)} 
         key={`tab-${index}`}>index</span>
})}

Try with React Fragments with a key attribute as mentioned in React docs

{tabContArr.map((section, index)=>{
    return <React.Fragment key={`section-tab-${index}`}>{section.tabTitle}</React.Fragment>
 })}

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