广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >react中使用forEach或map两种方式遍历数组
  • 746
分享到

react中使用forEach或map两种方式遍历数组

2024-04-02 19:04:59 746人浏览 八月长安
摘要

目录使用forEach或map两种方式遍历数组forEachmap循环遍历数组时map和forEach的区别forEach情况map 情况使用forEach或map两种方式遍历数组

使用forEach或map两种方式遍历数组

之前写代码,从后台提取数据并渲染到前台,由于有多组数据,用map遍历会相对方便一点,但是

map不能遍历array数组,只能遍历object对象。

所以如果遇到这样的问题可以采用forEach试一下

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;

在这里插入图片描述

循环遍历数组时map和forEach的区别

1. map函数返回一个新的数组,在map的回调函数里,迭代每一项的时候也必须有返回值。

2. forEach 没有返回值

forEach情况

import React, { Component } from "react"
import ListItem from './ListItem'
class TodoList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            inputValue: '',
            list: ['bb', 'ccc']
        };
        this.changeInput = this.changeInput.bind(this);
    }
    changeInput(e) {
        this.setState({
            inputValue: e.target.value
        })
    }
    commitInput = () => {
        const newList = JSON.parse(jsON.stringify(this.state.list));
        newList.push(this.state.inputValue);
        this.setState({
            list: newList,
            inputValue: ''
        })
    }
    deleteItem = index => {
        this.state.list.splice(index, 1);
        this.setState ({
            list: this.state.list
        })
    }
    componentDidMount() {
        console.log('parent didmount')
    }
    render() {
        console.log('parent render')
        const elements = [] 
        this.state.list.forEach((item, index) => {
            elements.push(
                <ListItem
                    key={index}
                    content={item}
                    index={index}
                    deleteItem={(index) => { this.deleteItem(index) }}
                />
            )
        })
        {
            console.log('zzz')
        }
        return (
            <div>
                <input type="text" value={this.state.inputValue} onChange={this.changeInput} />
                <button onClick={this.commitInput}>提交</button>
                <ul>
                    {
                        console.log('mmm')
                    }
                    {
                        elements    
                    }
                </ul>
                
                
            </div>
        )
    }
}
export default TodoList

map 情况

import React, { Component } from "react"
import ListItem from './ListItem'
class TodoList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            inputValue: '',
            list: ['bb', 'ccc']
        };
        this.changeInput = this.changeInput.bind(this);
    }
    changeInput(e) {
        this.setState({
            inputValue: e.target.value
        })
    }
    commitInput = () => {
        const newList = JSON.parse(JSON.stringify(this.state.list));
        newList.push(this.state.inputValue);
        this.setState({
            list: newList,
            inputValue: ''
        })
    }
    deleteItem = index => {
        this.state.list.splice(index, 1);
        this.setState ({
            list: this.state.list
        })
    }
    componentDidMount() {
        console.log('parent didmount')
    }
    render() {
        console.log('parent render')
        return (
            <div>
                <input type="text" value={this.state.inputValue} onChange={this.changeInput} />
                <button onClick={this.commitInput}>提交</button>
                <ul>
                    {
                        
                        this.state.list.map((item, index) => {
                            return(
                                <ListItem
                                    key={index}
                                    content={item}
                                    index={index}
                                    deleteItem={(index) => { this.deleteItem(index) }}
                                />
                            )
                        })
                    }
                </ul>
            </div>
        )
    }
}
export default TodoList

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。 

--结束END--

本文标题: react中使用forEach或map两种方式遍历数组

本文链接: https://www.lsjlt.com/news/167075.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • react中使用forEach或map两种方式遍历数组
    目录使用forEach或map两种方式遍历数组forEachmap循环遍历数组时map和forEach的区别forEach情况map 情况使用forEach或map两种方式遍历数组 ...
    99+
    2022-11-13
  • vue中数组遍历方法forEach和map怎么用
    这篇文章给大家分享的是有关vue中数组遍历方法forEach和map怎么用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。一、前言forEach和map是数组的两个方法,作用都是遍...
    99+
    2022-10-19
  • mybatis使用foreach遍历list集合或者array数组方式
    一、准备工作 1.db.properties文件(记得修改自己的数据库和用户名、密码) dataSource.driver=com.mysql.jdbc.Driver dataS...
    99+
    2022-11-12
  • JS数组遍历中for,forin,forof,map,forEach各自的使用方法与优缺点
    JS数组遍历普通函数 优点:支持流程控制(break、continue、return) for const arr = ["A", "B", "C"] for(let i = 0;...
    99+
    2022-11-13
  • PHP循环中如何使用foreach()方法遍历数组
    这篇文章主要介绍了PHP循环中如何使用foreach()方法遍历数组,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。foreach():for...
    99+
    2022-10-19
  • 怎么在jQuery中使用map方法遍历数组
    怎么在jQuery中使用map方法遍历数组?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。jquery是什么jquery是一个简洁而快速的JavaScript库,它具有独特的链式...
    99+
    2023-06-14
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作