Home > Article > Web Front-end > How to loop a list in react
React loop list method: 1. map loop, the code is [let MyDom =arr.map((item,index)=>]; 2. for loop, the code is [for(var i= 0;i
React loop list method:
1.map loop
<script type="text/babel"> let arr=["吃饭","睡觉","喝水"] let MyDom =arr.map((item,index)=>{ return <p>{item}</p> }) ReactDOM.render(MyDom,document.getElementById("demoReact")) </script>Traversal can be displayed on the page, console But an error was reported. The reason is that you have to set a unique key to facilitate subsequent operations on the array.After adding the key value, no error will be reported.
<script type="text/babel"> let arr=["吃饭","睡觉","喝水"] let MyDom =arr.map((item,index)=>{ //key值必须是独一无二的 return <p key={index}>{item}</p> }) ReactDOM.render(MyDom,document.getElementById("demoReact")) </script>If you want to change the code after return to Is it easy to just press Enter on the next line?
//直接回车换行 return <p key={index}>{item}</p>Of course it’s not easy to use. The solution is to use () to wrap the element, and it can be displayed normally after changing the line. So develop a habit: no matter how you change Add () without line breaks
//用括号包裹住换行元素 let MyDom =arr.map((item,index)=>{ return ( <p key={index}>{item}</p>) })
2.for in loop
function fun(){ let newarr=[]; for(let index in arr){ newarr.push(<p key={index}>{arr[index]}</p>) } return newarr; } ReactDOM.render(fun(),document.getElementById("demoReact"))
3.for loop
function fun(){ let newarr=[]; for(var i=0;i<arr.length;i++){ newarr.push(<p key={i}>{arr[i]}</p>) } return newarr; }
4.for each loop
function fun(){ arr.forEach(a=>{ console.log(a); }) }
Related free learning recommendations:javascript(video)
The above is the detailed content of How to loop a list in react. For more information, please follow other related articles on the PHP Chinese website!