简体   繁体   中英

React Warning: Each child in a list should have a unique "key" prop when key is provided and unique

I am rendering several list items from an api:

{clientSurveys &&
        clientSurveys?.map(({ data }, index) => (
          <ListItem
            key={data?.SurveyID}
            component={Link}
            to={`survey/${data?.SurveyID}`}
            disablePadding
            sx={{ color: 'inherit' }}
          >
)}

As seen above, I am providing a key (which is the id of the survey in this case):

key={data?.SurveyID}

Why am I keep getting this warning?

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

Why am I keep getting this warning?

The optional chaining ( ? ) in your key value suggests that the data might be undefined , so there's a chance that a couple of your items are getting the same key with undefined value.

key={data?.SurveyID} // it may end up with "undefined" value

You have to secure this case when data is undefined .

Its also worthy to mention that using the optional chaining in the key value is rather an anti pattern , because the key should be static and unique. data?.SurveyID also suggests that it might change over time.

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