溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

react有哪些遍歷方法

發(fā)布時(shí)間:2021-11-25 14:06:21 來(lái)源:億速云 閱讀:243 作者:iii 欄目:web開發(fā)

這篇文章主要講解了“react有哪些遍歷方法”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“react有哪些遍歷方法”吧!

react遍歷方法有:1、使用foreach()方法,語(yǔ)法“l(fā)ist.forEach((item)=>{...});”;2、使用map()方法,語(yǔ)法“l(fā)ist.map((item, index)=>{...});”。

react有哪些遍歷方法

本教程操作環(huán)境:Windows7系統(tǒng)、react17.0.1版、Dell G3電腦。

react采用forEach或map兩種遍歷方式

1、foreach(推薦)

  list.forEach((item)=>{
  
    });

例:

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)=>{

});

在React里map方法用于遍歷和顯示組件的類似對(duì)象列表,map不是React特有的,相反,它是可以在任何數(shù)組上調(diào)用的標(biāo)準(zhǔn)JavaScript函數(shù)。map()方法通過對(duì)調(diào)用數(shù)組中的每個(gè)元素調(diào)用提供的函數(shù)來(lái)創(chuàng)建新數(shù)組。

例:

var numbers = [1, 2, 3, 4, 5];   
const doubleValue = numbers.map((number)=>{   
    return (number * 2);   
});   
console.log(doubleValue);

在React中,map()方法用于:

1、遍歷列表元素。

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>  
          <h3>React Map例子</h3>  
              <ul>{listItems}</ul>  
    </div>  
  );  
}  
const myLists = ['A', 'B', 'C', 'D', 'D'];   
ReactDOM.render(  
  <NameList myLists={myLists} />,  
  document.getElementById('app')  
);  
export default App;

2. 用鍵遍歷列表元素。

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>  
      <h3>React Map例子</h3>  
          <ul> {listItems} </ul>  
    </div>  
  );  
}  
  
const numbers = [1, 2, 3, 4, 5];  
ReactDOM.render(  
  <NumberList numbers={numbers} />,  
  document.getElementById('app')  
);  
export default App;

感謝各位的閱讀,以上就是“react有哪些遍歷方法”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)react有哪些遍歷方法這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI