Home > Web Front-end > JS Tutorial > body text

How to loop a list in react

coldplay.xixi
Release: 2020-11-26 16:48:32
Original
5496 people have browsed it

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

How to loop a list in react

  • ##This method is suitable for all brands of computers

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>)
        })
Copy after login

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"))
Copy after login

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;
        }
Copy after login

4.for each loop

 function fun(){
            arr.forEach(a=>{
             console.log(a);
            })
        }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template