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