Home  >  Article  >  Web Front-end  >  How to loop a list in react

How to loop a list in react

coldplay.xixi
coldplay.xixiOriginal
2020-11-26 16:48:325472browse

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>

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!

Statement:
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

Related articles

See more