react 中怎么遍历数组? 下面本篇文章给大家介绍一下在 react 中遍历数组的方法. 有一定的参考价值, 有需要的朋友可以参考一下, 希望对大家有所帮助.
react 采用 forEach 或 map 两种方式遍历数组
forEach() 方法用于调用数组的每个元素, 并将元素传递给回调函数.
map() 方法返回一个新数组, 数组中的元素为原始数组元素调用函数处理后的值.
map() 方法按照原始数组元素顺序依次处理元素.
- 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}
- <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}
- <a>{item.address}</a>
- <hr/>
- </div>
- )
- )
- }
- }
- export default forEach;
更多 web 前端开发 https://www.html.cn/ 知识, 请查阅 HTML 中文网 !!
来源: http://www.css88.com/qa/react/16974.html