循环渲染数组数据,推荐使用map函数,当然,也可以使用forEach函数,两者有差别,但差别不大,全看个人喜好了
1.forEach
~~~
import React,{ Component } from 'react'
class TestArray extends Component{
render(){
const arr = [1,2,3,4,5];
var newArr = [];
arr.forEach((ele,index)=> {
var temp = <li key={index}>{ele}</li>
newArr.push(temp)
})
return <ul>
{newArr}
</ul>
}
}
export default TestArray
~~~
2.1map
>[success] 咋一看跟forEach用法一样,然而 F12打开调试发现有条警告,是的,map函数遍历项时可以有返回值的,(像:arr.map(ele=> { return ele }))不添加也没关系,但添上更好
~~~
import React,{ Component } from 'react'
class TestArray extends Component{
render(){
const arr = [1,2,3,4,5];
var newArr = [];
arr.map((ele,index)=> {
var temp = <li key={index}>{ele}</li>
newArr.push(temp)
})
return <ul>
{newArr}
</ul>
}
}
export default TestArray
~~~
2.2map
>[success] map与forEach不一样,var temp1 = arr.forEach(ele=> {}),var temp2 = arr.map(ele=> { return ele }) ,在控制台输出时会发现前者为undifined,后者为arr数组复制,所以在React中,可以直接写成类似下例的样子
~~~
import React,{ Component } from 'react'
class TestArray extends Component{
render(){
const arr = [1,2,3,4,5];
return <ul>
{arr.map((ele,index)=>{
return <li key={index}>{ele}</li>
})}
</ul>
}
}
export default TestArray
~~~