Most efficient way of rendering JSX elements when

2019-02-08 15:43发布

I have an array which contains objects. I am creating a map of this array to renders the names with a span component.

let data = [{"id": "01", "name": "Hi"}, {"id": "02", "name": "Hello"}];

I have been using the below two different functionalities to iterate on that array of objects, and using map to render JSX elements.

Functionality1:

import React, { Component } from 'react';
class App extends Component {

  render() {
    let data = [{"id": "01", "name": "Hi"}, {"id": "02", "name": "Hello"}];
    const items = data.map((key, i) => {
      return <span key={key.id}>{key.name}</span>;
    });
    return (
      <div>
        {items}
      </div>
    );
  }
}

export default App;

Functionality2:

import React, { Component } from 'react';
class App extends Component {

  render() {
    let data = [{"id": "01", "name": "Hi"}, {"id": "02", "name": "Hello"}];
    let rows = [];
    data.map((key, i) => {
      rows.push(<span key={key.id}>{key.name}</span>);
    });
    return (
      <div>
        {rows}
      </div>
    );
  }
}


export default App;

I known to the above two different ways of using map and rendering JSX elements. Is there any other ways of doing the same, apart from these two? If so, which is recommended?

8条回答
We Are One
2楼-- · 2019-02-08 16:25

The first way is better.

  1. Array.prototype.map creates an array behind the scenes and returns it after applying the modification on each element. Functionality-1 creates two arrays, while Functionality-2 creates three.

  2. Functionality-1 reads better. It's how React code usually being written. For a simple element like this, I'd save the const definition for items and put the map statement in the JSX to be returned directly.

查看更多
我命由我不由天
3楼-- · 2019-02-08 16:27

Generally, for or while statement is the most efficient way to iterate an array. The way a small array is processed in non-critical place can be considered microoptimisation.

The use of map is idiomatic in React components because it's fast enough and can return a value as a part of an expression.

While this is an antipattern:

let rows = [];
data.map((key, i) => {
  rows.push(<span key={key.id}>{key.name}</span>);
});

map is supposed to map array elements to other values (hence the name), not to iterate an array instead of forEach or other loop. This problem can be tracked with ESLint array-callback-return rule.

The component is stateless and doesn't need to be Component class. It can be functional component or PureComponent class. Since data is constant, it doesn't need to be assigned on each render:

const data = [{"id": "01", "name": "Hi"}, {"id": "02", "name": "Hello"}];

const App = props => <div>
  {data.map(({ id, name }) => <span key={id}>{name}</span>)}
</div>;
查看更多
登录 后发表回答