Understanding unique keys for array children in React.js

后端 未结 12 1337
时光取名叫无心
时光取名叫无心 2020-11-21 05:45

I\'m building a React component that accepts a JSON data source and creates a sortable table.
Each of the dynamic data rows has a unique key assigned to it but I\'m stil

12条回答
  •  旧巷少年郎
    2020-11-21 06:23

    In ReactJS if you are rendering an array of elements you should have a unique key for each those elements. Normally those kinda situations are creating a list.

    Example:

    function List() {
      const numbers = [0,1,2,3];
     
      return (
        
      {numbers.map((n) =>
    • {n}
    • )}
    ); } ReactDOM.render( , document.getElementById('root') );

    In the above example, it creates a dynamic list using li tag, so since li tag does not have a unique key it shows an error.

    After fixed:

    function List() {
      const numbers = [0,1,2,3];
     
      return (
        
      {numbers.map((n) =>
    • {n}
    • )}
    ); } ReactDOM.render( , document.getElementById('root') );

    Alternative solution when use map when you don't have a unique key (this is not recommended by react eslint ):

    function List() {
      const numbers = [0,1,2,3,4,4];
     
      return (
        
      {numbers.map((n,i) =>
    • {n}
    • )}
    ); } ReactDOM.render( , document.getElementById('root') );

    Live example: https://codepen.io/spmsupun/pen/wvWdGwG

提交回复
热议问题