React trick 2 (avoid meaningless parent nodes)

React trick 2 (avoid meaningless parent nodes)

There are 5 articles in this tutorial, one updated daily, please follow us! You can enter the historical news to view the previous articles, and stay tuned for our new articles!

1.React Tip 1 (Use of Stateful Components and Stateless Components) ----2018.01.04

2.React Tip 2 (Avoid meaningless parent nodes)----2018.01.05

3.React Skill 3 (How to render a List gracefully)----2018.01.06

4.React Skill 4 (How to deal with the Item in the List)----2018.01.07

5.React technique 5 (TodoList implementation) ----2018.01.08

Development environment: Windows 8, node v8.9.1, npm 5.5.1, WebStorm 2017.2.2

We often encounter such situations when we are developing?

For example, I put

<i className="bd_logo1"/>
This is {this.props.title}

Separate these two lines of code and put them in two div.top

<div className="top">
    
</div>
<div className="top">
    <i className="bd_logo1"/>
</div>
<div className="top">
    This is {this.props.title}
</div>

Then I want to make this piece of code into a component!

New SecondsTop.jsx component

Put the code directly in, it will report an error, we must put it in a label.

For example, put them in a div parent tag!

import React from'react';

const SecondsTop = ({title}) =>
    <div>
        <div className="top">
            <i className="bd_logo1"/>
        </div>
        <div className="top">
            This is {title}
        </div>
    </div>
;

export default SecondsTop;

We introduce the SecondsTop.jsx component in Seconds.jsx

Check it out in the browser!

You will find an extra layer of meaningless div parent tags! It is meaningless and affects performance (very small)

How can we avoid it!

Transform the SecondsTop.jsx component and directly return an array

import React from'react';

const SecondsTop = ({title}) => [
    <div className="top">
        <i className="bd_logo1"/>
    </div>,
    <div className="top">
        This is {title}
    </div>
];
export default SecondsTop;

Look at the browser again

That meaningless div parent tag is no longer needed!

But the browser will report an error!

We only need to add KEY to him and transform it again!

import React from'react';

const SecondsTop = ({title}) => [
    <div className="top" key="top1">
        <i className="bd_logo1"/>
    </div>,
    <div className="top" key="top2">
        This is {title}
    </div>
];
export default SecondsTop;

Look at the browser again

Everything is ok, OK!

It is often encountered in development, everyone must apply flexibly, and the writing method despise is only available in react16 and above!

Reference: https://cloud.tencent.com/developer/article/1092767 React Tip 2 (Avoid meaningless parent nodes)-Cloud + Community-Tencent Cloud