Understanding unique keys for array children in React.js

后端 未结 12 1294
时光取名叫无心
时光取名叫无心 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:26

    You should add a key to each child as well as each element inside children.

    This way React can handle the minimal DOM change.

    In your code, each is trying to render some children inside them without a key.

    Check this example.

    Try removing the key={i} from the element inside the div's (and check the console).

    In the sample, if we don't give a key to the element and we want to update only the object.city, React needs to re-render the whole row vs just the element.

    Here is the code:

    var data = [{name:'Jhon', age:28, city:'HO'},
                {name:'Onhj', age:82, city:'HN'},
                {name:'Nohj', age:41, city:'IT'}
               ];
    
    var Hello = React.createClass({
    
        render: function() {
    
          var _data = this.props.info;
          console.log(_data);
          return(
            
    {_data.map(function(object, i){ return
    {[ object.name , // remove the key {object.city} , object.age ]}
    ; })}
    ); } }); React.render(, document.body);

    The answer posted by @Chris at the bottom goes into much more detail than this answer. Please take a look at https://stackoverflow.com/a/43892905/2325522

    React documentation on the importance of keys in reconciliation: Keys

提交回复
热议问题