react conditional rendering&list&key

Conditional rendering

Conditional rendering is relatively simple, just read the relevant documentation on the official website .

list

Render the list via map:

class HelloWorld extends React.Component {
  constructor(props){
    super(props);
    this.state = ({
      arr: [1,2,3,4]
    })
  }  
  render(){
    return (
      <ul>
        {
          this.state.arr.map(item=>(
            <li>li_{item}</li>
          ))
        }  
      </ul>
    )
  }
}
// 通过调用React自身方法render可以得到当前组件的实例对象,并渲染到页面容器.
ReactDOM.render(<HelloWorld />,document.getElementById('root'));

key

We found an error,  Each child in a list should have a unique "key" prop. which means that each element we traverse should have a unique key. This is the same as Vue and is used to distinguish components when react is rendering at the bottom. In principle, we cannot use the subscript of an array as a key. Because the addition and deletion of the array will affect the subscript, a unique value should be provided for the data. Each item we determine
here is unique, and we can use the value as the key. In actual development, it is recommended to use the id of the array element object as the key.arr

class HelloWorld extends React.Component {
  constructor(props){
    super(props);
    this.state = ({
      arr: [1,2,3,4]
    })
  }  
  render(){
    return (
      <ul>
        {
          this.state.arr.map(item=>(
            <li key={item}>li_{item}</li>
          ))
        }  
      </ul>
    )
  }
}
// 通过调用React自身方法render可以得到当前组件的实例对象,并渲染到页面容器.
ReactDOM.render(<HelloWorld />,document.getElementById('root'));

 

Guess you like

Origin blog.csdn.net/m0_67388537/article/details/131954719