{return
Home > Article > Web Front-end > What is the usage of map in react
Usage of map in react: 1. Use "{this.state.ToDoList.map((item,index)=>{return
{item}})}" syntax loops to display an array ToDoList; 2. Use the array to call the "map()" method and return the desired content.
The operating environment of this tutorial: Windows 10 system, react version 18.0.0, Dell G3 computer.
What is the usage of map in react?
The use of the map() method in React and the binding of key values.
1. Here is an example of displaying an array ToDoList in a loop.
import React, { Component } from 'react' export default class App extends Component { constructor(props) { super(props) this.state = { ToDoList:[1,2] } } render() { return ( <div> <input></input><button>提交</button> <ul> {this.state.ToDoList.map((item,index)=>{ return <li key={index}>{item}</li> })} </ul> </div> ) } }
2. Call the map() method directly with an array, return the content you want, and bind the key value.
<ul> {this.state.ToDoList.map((item,index)=>{ return <li key={index}>{item}</li> })} </ul>
2.1 For convenience, the bound key value here is the subscript of the array. This is not recommended in actual use, because when the Diff algorithm in React performs component comparison, if the key called is the array subscript, Changes to the array will cause the array content corresponding to the subscript to be incorrect. For example,
[1,2,3] will become [2,3] after deleting 1, and
will be originally subscripted. Subscript 0 corresponds to 1, subscript 1 corresponds to 2, and subscript 2 corresponds to 3. After the change, subscript 0 corresponds to 2, and subscript 1 corresponds to 3. Obviously this will cause trouble for the Diff algorithm when comparing two virtual DOMs. Because the corresponding content is different when the id is the same, and the meaning of the id is lost. Therefore, it is not recommended to use array subscripts as key values. This is written based on my own understanding. There may be some misunderstandings. Anyway, this is the general meaning. Please correct me if there are any mistakes.
3. The running result is as shown below
Recommended learning: "react video tutorial"
The above is the detailed content of What is the usage of map in react. For more information, please follow other related articles on the PHP Chinese website!