Most efficient way of rendering JSX elements when iterating on array of data in React

后端 未结 8 1206
無奈伤痛
無奈伤痛 2020-12-09 17:42

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\         


        
8条回答
  •  萌比男神i
    2020-12-09 18:25

    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({key.name});
    });
    

    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 => 
    {data.map(({ id, name }) => {name})}
    ;

提交回复
热议问题