Different ways to add a key to JSX element in loop in React

前端 未结 4 1257
天涯浪人
天涯浪人 2020-12-10 14:25

I have been working on react for more than an year now. I have mostly played with iterating an array using .map, .forEach, .filter or using Object.keys and Object.values if

4条回答
  •  粉色の甜心
    2020-12-10 15:02

    The best way to pick a key is to use a string that uniquely identifies a list item among its siblings. Most often you would use IDs from your data as keys:

    const todoItems = todos.map((todo) =>
      
  • {todo.text}
  • );

    When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort:

    const todoItems = todos.map((todo, index) =>
      // Only do this if items have no stable IDs
      
  • {todo.text}
  • );

    Also note:

    Keys used within arrays should be unique among their siblings. However they don’t need to be globally unique.

    However real answer to your question lives here: https://medium.com/@robinpokorny/index-as-a-key-is-an-anti-pattern-e0349aece318

    There are many libraries that generate random unique ids such as shortid or uuid (which is the most popular one, just look at the number of downloads) or else just create your own function that generates random strings.

    You can add them directly into object in array

    const todos = [
      { 
        id: uuid(),
        text: 'foo',
      }
    ]
    

    and iterate like so:

    const todoItems = todos.map(({id, text}) =>
      
  • {text}
  • );

提交回复
热议问题