admin管理员组文章数量:1399987
I have a question. How can I generate key for array of string? It is not object, in object I could put id and it would solve the problem. So what should I do in just array? Indexes as key is not a good practice so I am stuck.
const ingredients = ['rice', 'curry', 'chicken]
{props.ingredients.map((ingredient) => (
<Box>{ingredient}</Box>
))}
I have a question. How can I generate key for array of string? It is not object, in object I could put id and it would solve the problem. So what should I do in just array? Indexes as key is not a good practice so I am stuck.
const ingredients = ['rice', 'curry', 'chicken]
{props.ingredients.map((ingredient) => (
<Box>{ingredient}</Box>
))}
Share
Improve this question
asked Feb 19, 2022 at 19:58
KayKay
8914 gold badges13 silver badges35 bronze badges
0
4 Answers
Reset to default 6If you don't have any duplicate ingredients, using the ingredient name as the key would be fine.
{props.ingredients.map((ingredient) => (
<Box key={ingredient}>{ingredient}</Box>
))}
If you will have duplicate ingredients, and you really care about getting the key right, you could use the index if the index won't change:
{props.ingredients.map((ingredient, i) => (
<Box key={i}>{ingredient}</Box>
))}
(Using the index isn't universal bad practice, it's just only suitable for some situations)
If you could have duplicate ingredients and the index can change, and you really want to fix this, change it to an array of objects instead of an array of strings, with a uniquely identifying attribute on each object that you can use as a key.
const ingredients = ['rice', 'curry', 'chicken']
{props.ingredients.map((ingredient, index) => (
<Box key={index}>{ingredient}</Box>
))}
{props.ingredients.map((ingredient, index) => (<Box key={index}>{ingredient}</Box>))}
You get an index built in when doing it like this and can use it as they key.
When you use map, it's better to specify key for selected ponent inside map function. first parameter in map function is value from given list and second one is index of item in list. you can name second parameter as whatever you want and pass it as key to ponent like this:
const ingredients = ['rice', 'curry', 'chicken]
{props.ingredients.map((ingredient, index) => (
<Box key={index}>{ingredient}</Box>
))}
本文标签: javascriptReact keys for an array of stringsStack Overflow
版权声明:本文标题:javascript - React keys for an array of strings - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744194559a2594676.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论