文档章节

React JSX

Kolosek
 Kolosek
发布于 2018/02/08 20:35
字数 746
阅读 5
收藏 0

Usually, when developing a website, you'll need some dynamical rendering, like a listing of items, showing some element under a certain condition and so on.
You're all aware of the standard JS syntax - a  for loop, or an if / else  - but when you try to write those under a render method in React, you'll most likely get some weird looking errors.

In this, the first part of React JSX series, we will take a look at how to correctly loop through arrays the reactive way.

Please note that all of the examples below apply as well to React Native!

Using loops inside React render methods

Let's say you have an array of movies and that you need to display the Movie component for each of them.

Most of us have tried this at some point:

render() {
    return (
        <div>
            {
                // this won't work!
            }
            {
                for (var i=0; i < movies.length; i++) {
                    <Movie movie={movie} />
                }
            } 
        </div>
    )
}

This, however, will not work.  Why? Think of it like you're just calling JavaScript functions. You can not put a for loop as a parameter when calling a function!

Well, how to do it then?  There are a few ways.
You can go through a for loop above the return statement in render method and fill in a list you'll pass in return:

render() {
    const movieItems = [];
    for (var i=0; i < movies.length; i++) {
        movieItems.push(<Movie movie={movie} />);
    }
    return (
        <div>
            {
                movieItems
            } 
        </div>
    )
}

This, however, is not a neat way as it's polluting the render method. To make render more readable, better move the for loop outside of it and then call it as a function:

renderMovies(movies) {
    const movieItems = [];
    for (var i=0; i < movies.length; i++) {
        movieItems.push(<Movie movie={movie} />);
    }
    return movieItems;
}

render() {
    return (
        <div>
            {
                this.renderMovies(movies)
            } 
        </div>
    )
}

This looks a bit better now. Still, you are using the for loop which does not really look so nice. The for should be used when you need to render something a certain number of times. When you have an object or an array instead there are neater ways

So, let's switch to using the  map  from JS Arrays:

renderMovies(movies) {
    // This is ES6 syntax! You'll need babel configured to use it!
    // You can still use the standard function syntax,
    // but ES6 is definitely something that'll easen your life.
    return movies.map((movie) => {
        return (
            <Movie movie={movie} />
        );
    });
}

render() {
    return (
        <div>
            {
                this.renderMovies(movies)
            } 
        </div>
    )
}

Now, this looks good! Yet, it might look a bit bulky for being just a simple listing you can do in one single place. However, the map syntax you can actually use directly in a return statement. Why? Because the map function basically passes a freshly created array, compared to the for loop which is just a bulk of code.

render() {
    return (
        <div>
            {
                // This is shortened syntax, for where we don't need to manipulate the actual items before rendering them
            }
            {
                movies.map((movie) => <Movie movie={movie} />)
            } 
        </div>
    )
}

When you need to manipulate the actual item in the list before rendering it, you can do it this way:

render() {
    return (
        <div>
            {
                movies.map((movie) => {
                    // do something with a movie here
                    return (
                        <Movie movie={movie} />
                    );
                })
            } 
        </div>
    )
}

Now, again, if there's a lot of manipulating to be done for a single item, doing it inside a return statement might imposedDivlute the render method. In that case, better move this code out of the render method. Here's an example:

renderMovie(movie) {
    // do something with a movie here
    return (
        <Movie movie={movie} />
    );
}

render() {
    return (
        <div>
            {
                // map will automatically pass the list item to our function
            }
            {
                movies.map(this.renderMovie)
            } 
        </div>
    )
}

All of the previous can also be used for JavaScript objects, with slight adaptation - you will not be mapping through the object, but through the list of the keys of the object:

render() {
    return (
        <div>
            {
                // You can as well use lodash keys function (_.keys)
                // instead of Object.keys, but it functions the same way
            }
            {
                Object.keys(moviesObject).map((movieKey) => {
                    const movie = moviesObject[movieKey];
                    return (
                        <Movie
                            key={movieKey}
                            movie={movie}
                        />
                    );
                })
            } 
        </div>
    )
}

Keep in mind that all of the codes above are just examples, pseudo codes.  Always send the key prop to the items you're rendering and keep it unique, avoiding array indexes.

Now you know multiple ways on how to loop through arrays in React! Which way you'll use is up to you and the occasion, sometimes one will be more suitable than the other.

Thank you for your time and good luck with coding!

Did you like this article? In the next part, we'll be covering conditional rendering in React.

Originally published on kolosek.com .

 

© 著作权归作者所有

Kolosek
粉丝 0
博文 29
码字总数 20461
作品 0
塞尔维亚
CEO
私信 提问
[3]React 深入浅出-----JSX简介

在使用React的时候,就不得不提JSX, JSX可以理解为JavascriptXML,其标准的官方网站为:https://github.com/jsx/JSX,安装JSX也很简单: E:Reactlearn>npm install -g jsxC:UsersrodneyAppD...

chancein007
2017/08/06
0
0
react16 源码阅读学习记录

React源码系列(一): 总结看源码心得及方法感受 React源码系列(二): 从jsx到createElement React源码系列(三): ReactRoot的创建以及调度工作scheduleWork的执行 React源码系列(四): Fiber Tr...

大灰狼的小绵羊哥哥
2018/12/08
0
0
React学习(2)-深入浅出JSX

前言 在Jq,原生javascript时期,在写页面时,往往强调的是内容结构,层叠样式,行为动作要分离,三者之间分工明确,不要耦合在一起 然而在React出现后,一切皆js,对于在JS里面写HTML代码,刚开始是非...

itclanCoder
07/03
0
0
从零开始 2,react -快速上手

什么是React A JAVASCRIPT LIBRARY FOR BUILDING USER INTERFACES 用来构建UI的 JavaScript库React 不是一个 MVC 框架,仅仅是视图(V)层的库 特点 为什么要用React React中的核心概念 虚拟...

NDweb
2018/07/31
15
0
React.js 实战之 JSX 简介

在项目中引入并使用 JSX 这种看起来可能有些奇怪的标签语法既不是字符串也不是 HTML 它被称为 JSX, 一种 JavaScript 的语法扩展 推荐在 React 中使用 JSX 来描述用户界面 JSX 乍看起来可能比...

JavaEdge
2018/12/01
0
0

没有更多内容

加载失败,请刷新页面

加载更多

宜信微服务任务调度平台建设实践|分享实录

内容来源:宜信技术学院第4期技术沙龙-线上直播|宜信微服务任务调度平台建设实践 主讲人:宜信高级架构师 开发平台负责人 梁鑫 导读:如今,无论是互联网应用还是企业级应用,都充斥着大量的...

宜信技术学院
2分钟前
0
0
concat和concat_ws

select concat('大','小') as size from 表 查询出结果为:大小 select concat('大',NULL) as size from 表 查询出结果为:null concat中又一个参数为NULL,查出来的就为NULL select concat_......

郭周园
12分钟前
0
0
Java设计模式六大原则

一.单一职责原则   单一职责原则是最简单的面向对象设计原则,它用于控制类的粒度大小。单一职责原则定义如下: 单一职责原则(Single Responsibility Principle, SRP):一个类只负责一个功...

asdf08442a
20分钟前
2
0
解读MySQL性能调优“金字塔”

计算机是一种实验的科学,性能优化是实战的艺术 蒸汽机的改进不是一蹴而就的,MySQL性能的改进也是贯穿整个MySQL发展史的。MySQL之父Monty在1981年写了MySQL的第一行代码以后,在开源的帮助下...

博文视点Bv
23分钟前
2
0
直播系统源码必备的几个功能

网络直播平台发展至今,除了在经营上涉及的行业越来越多之外,随着产品的升级,也演化出了多种多样表达形式,除了传统的一对多直播间,近些年不久盛行的一对一直播或是短视频 直播等。 APP手...

布谷科技
24分钟前
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部