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


轉載:

版權聲明:本文為博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。

原文鏈接:https://blog.csdn.net/dayexiaofan/article/details/86707074

 

之前寫代碼,從后台提取數據並渲染到前台,由於有多組數據,用map遍歷會相對方便一點,但是
map不能遍歷array數組,只能遍歷object對象。

所以如果遇到這樣的問題可以采用forEach試一下

import React,{Component} from 'react';
let list=[
  {
    name:"百度",
    address:"http://www.baidu.com"
  },
  {
    name:"google",
    address:"http://www.google.cn"
  },
  {
    name:"firefox",
    address:"https://home.firefoxchina.cn"
  }
];
class forEach extends Component{
  render(){
    //定義一個數組,將數據存入數組
    const elements=[];
    list.forEach((item)=>{
      elements.push(
        <div>
          {item.name}&nbsp;
          <a>{item.address}</a>
          <hr/>
        </div>
      )
    });
    return(
      <div>
        {elements}
      </div>
    )
  }
}
export default forEach;

 

 

map

import React,{Component} from 'react';
let list=[
  {
    name:"百度",
    address:"http://www.baidu.com"
  },
  {
    name:"google",
    address:"http://www.google.cn"
  },
  {
    name:"firefox",
    address:"https://home.firefoxchina.cn"
  }
];
class forEach extends Component{
  render(){
    return(
    list.map((item)=>
        <div>
          {item.name}&nbsp;
          <a>{item.address}</a>
          <hr/>
        </div>
      )
    )
  }
}
export default forEach;

 

謝謝

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM