React learning: List && Key

In React in the array into the element, and the map method similar js, returns an array of elements of the class

1. render multiple components

{} May be used to build a collection of element jsx

const number = [1, 2, 3, 4, 5, 6];
const listItem = number.map((item)=>{
    return <li>{item}</li>
})
ReactDOM.render( <ul>{listItem} </ul>,document.getElementById('root'))

2. Basic component list

Usually you need to render a list of components, rather than build a set of elements can now be pulled out of the building above is a component.

// 列表 && Key,渲染为组件去使用
const number = [1, 2, 3, 4, 5, 6];
function NumberList(props){
    const listItem = props.numbers.map((item)=>
        <li>{item}</li>
    )
    return (
        <ul>{listItem}</ul>
    )
}
ReactDOM.render( <NumberList numbers={number} />, document.getElementById('root'))

At this point there is no key operation will report a warning, you need to add the key (with Vue as key for the identity cycle), the following will introduce key

const listItem = props.numbers.map((item,index)=>
     <li key={index}>{item}</li>
)

 

3. With regard to key

React 1.key help identify what elements change (add / delete), it is necessary to add the key to every element in the array.

2.key as identification element is essential and unique, we usually use id to identify, if there is no other time can be identified, but also allows the use of index, but this time to note,

If the order of the list of items may change, is not recommended to use the index as a key value, because to do so would result in poor performance, it may also cause problems in the state assembly.

3. react, no globally unique key, only need to identify key sibling is unique to.

4.key will only pass to react, and not to transfer to sub-assemblies, if the information key sub-components also need parent component, you need to use other property name is passed

5 may be nested in jsx the map (), but not abuse this style, cause code is not clear. If the map () nested too, need to be considered extraction assembly

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

      )}
    </ul>
  );
}

 

Guess you like

Origin www.cnblogs.com/liyaping/p/11586462.html