Key
  • Help React to update only the necessary elements instead of re-rendering the entire list when something changes
  • Do not pass to the assigned component
  • When the component list is updated, the reconciler will look at the key, and the component properties in the updated component list, and then look through its previous list of components to see if it matches any previous combinations
  • import React from 'react';
    import ReactDOM from 'react-dom';
    
    class App extends React.Component{
    	  constructor(props) {
    		    super(props)
    		    this.state = {
    			      list: [{id: 1,val: 'aa'}, {id: 2, val: 'bb'}, {id: 3, val: 'cc'}]
    		    }
    	  }
    
    	  click() {
    		  this.state.list = [{id: 1,val: 'aa'}, {id: 2, val: 'bb'}, {id: 6, val: 'ee'}]
    		    //this.state.list.reverse()
    		    this.setState({list: [...this.state.list, {id: 4, val: 'dd'}]})
    	  }
    
    	  render() {
    		    return (
                <ul>
                    <div onClick={this.click.bind(this)}>Update</div>
                    {
                    	this.state.list.map(function(item, index) {
                    		return (
                                <Li key={item.id} val={item.val}></Li>
                    		)
                    	}.bind(this))
                    }
                </ul>
    		    )
    	  }
    }
    
    class Li extends React.Component{
    	  constructor(props) {
    		    super(props)
    	  }
    	  componentDidMount() {
    		    console.log('===Did Mount===');
    		    console.log(this.props);
    	  }
    	  componentWillUpdate(nextProps, nextState) {
    		    console.log('===Will Update====');
    		    console.log(nextProps);
    		    console.log(nextState);
    	  }
    	  componentDidUpdate(prevProps, prevState) {
    		  console.log('===Did Update===');
    		  console.log(prevProps);
    		  console.log(prevState);
    	  }
    	  render() {
    		    return (
                <li>
                    {this.props.val}
                </li>
    		    )
    	  }
    }
    
    ReactDOM.render(<App />, document.getElementById('root'));
    		
    Reference
  • The significance of React keys - a visual explanation