The react traversal methods are: 1. Use the foreach() method, the syntax "list.forEach((item)=>{...});"; 2. Use the map() method, the syntax " list.map((item, index)=>{...});".
The operating environment of this tutorial: Windows7 system, react17.0.1 version, Dell G3 computer.
react uses forEach or map two traversal methods
1. foreach (recommended)
list.forEach((item)=>{ });
Example:
dataSource.forEach((item) => { const est = item.estimateAmount === null ? 0 : parseFloat(item.estimateAmount); const gmv = item.estimateGmv === null ? 0 : parseFloat(item.estimateGmv); allCountBudget += est; allCountGmv += gmv; // allCountGmv = parseFloat(allCountGmv) + parseFloat(gmv); });
2. map
list.map((item, index)=>{ });
In React, the map method is used to traverse and display a list of similar objects of the component. Map is not unique to React. On the contrary, it is a standard JavaScript that can be called on any array. function. The map() method creates a new array by calling the provided function on each element in the calling array.
Example:
var numbers = [1, 2, 3, 4, 5]; const doubleValue = numbers.map((number)=>{ return (number * 2); }); console.log(doubleValue);
In React, the map() method is used for:
1. Traverse list elements.
import React from 'react'; import ReactDOM from 'react-dom'; function NameList(props) { const myLists = props.myLists; const listItems = myLists.map((myList) => <li>{myList}</li> ); return ( <div> <h2>React Map例子</h2> <ul>{listItems}</ul> </div> ); } const myLists = ['A', 'B', 'C', 'D', 'D']; ReactDOM.render( <NameList myLists={myLists} />, document.getElementById('app') ); export default App;
2. Traverse the list elements by key.
import React from 'react'; import ReactDOM from 'react-dom'; function ListItem(props) { return <li>{props.value}</li>; } function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => <ListItem key={number.toString()} value={number} /> ); return ( <div> <h2>React Map例子</h2> <ul> {listItems} </ul> </div> ); } const numbers = [1, 2, 3, 4, 5]; ReactDOM.render( <NumberList numbers={numbers} />, document.getElementById('app') ); export default App;
Recommended learning: "react video tutorial"
The above is the detailed content of What are the react traversal methods?. For more information, please follow other related articles on the PHP Chinese website!