天行健, 君子以自强不息
Sunny's Blog
Title

React Keys

react要求在动态添加例如多个li的元素的时候,添加一个特殊属性key,这个主要是从react的diff算法特性上考虑的。

1.添加key

                    function NumberList(props){
                         const number = props.number;
                         const listItems = number.map((number)=>{
                             <li key={number.toString()}>
                                 {number}
                             </li>
                         });
                         return (
                             <ul>{listItems}</ul>
                         );
                    }

                    const numbers = [1, 2, 3, 4, 5];
                    ReactDOM.render(
                       <NumberList numbers={numbers} />,
                       document.getElementById('root')
                    );

                    //NumberList是components的function的写法,也可以写成class
            

1):key的选择最好是固定的,在组件内要求是唯一的,但是不要求全局唯一

2):不推荐用index作为key,因为index可能是会变化的

3):key要添加在map的逻辑中,而不应该添加在不循环的子组件中(A good rule of thumb is that elements inside the map() call need keys.)

4):可以像上面一样把listItems提取出来赋值给变量,也可以直接写在ul中,添加在{}里面就可以了

2.Reconciliation

Reconciliation是react通过diffing算法后rerender的过程的专有名词,简单来说react对比前后两个render tree的高效方式主要基于两点:

1):如果elements的根元素类型不同,就替换elements. 如果类型一样属性不一样就只换属性

                    // This will destroy the old Counter and remount a new one.
                    <div>
                        <Counter />
                    </div>
                    
                    <span>
                        <Counter />
                    </span>

                    // By comparing these two elements, React knows to only modify the className on the underlying DOM node.
                    <div className="before" title="stuff" />
                    <div className="after" title="stuff" />
            

2):有些子元素前后两次render的顺序不一样但实际没有变化,developer会加一个key元素作为提示

                    //没有添加key的时候,前后两次会使得性能变差
                     <ul>
                       <li>Duke</li>
                       <li>Villanova</li>
                     </ul>

                     <ul>
                       <li>Connecticut</li>
                       <li>Duke</li>
                       <li>Villanova</li>
                     </ul>
                    
                    // 添加之后react的diffing性能提升
                    <ul>
                       <li key="2015">Duke</li>
                       <li key="2016">Villanova</li>
                    </ul>

                    <ul>
                       <li key="2014">Connecticut</li>
                       <li key="2015">Duke</li>
                       <li key="2016">Villanova</li>
                    </ul>
            
地势坤,君子以厚德载物