Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Mostly, I follow this rule:

Create a component which renders the items

// in some file
export const RenderItems = ({data}) => {
  return data && data.map((d, i) => <span key={d.id}>{d.name}</span>) || null
}

Hook the RenderItems

import { RenderItems } from 'some-file'

class App extends Component {
  render() {
    // you may also define data here instead of getting data from props
    const { data } = this.props
    return (
      <div>
        <RenderItems data={data} />
      </div>
    )
  }
}

Attach the data in the component

const data = [{"id": "01", "name": "Hi"}, {"id": "02", "name": "Hello"}]
<App data={data} />

Following this rule will not impact on performance even with your second example of code ie. pushing items in an array and rendering the items. Because, you're not directly working inside the render hook. Always take care that render hook wouldn't implement any logic inside it directly.


Further, I wouldn't create id just for using key:

const data = [{"name": "Hi"}, {"name": "Hello"}]
//... and when using index as key
.map((d, i) => <span key={'item-'+i}>
// or,
.map((d, i) => <span key={'item-'+i+'-'+d.name}>

See this post why I follow this syntax while using index as key.


Update:

If you want to avoid unnecessary html tags being used, you can use React.Fragment

export const RenderItems = ({data}) => {
  return data && 
    data.map(
      (d, i) => <React.Fragment key={d.id}>{d.name}</React.Fragment>
    ) || null
}
// and when rendering, you just return the component
return <RenderItems data={data} />

Note:

  1. You can use <></> as an alias for <React.Fragment></React.Fragment> only if you don't have any additional property. Since we're using key property on it, not using it.
  2. Take a look at this to make support for short notation of React.Fragment.

Example using <></>:

<>{d.name}</>

This will be rendered d.name's value in html without any tag. This is considered best when we specifically transform our existing design to react application. Or, there might be other cases. Like, we are going to display a definition list:

<dl>
  <dt></dt>
  <dd></dd>
  <dt></dt>
  <dd></dd>
  <dt></dd>
</dl>

And we don't want to attach unnecessary html tag, then using Fragment will make our life easier:

Example:

<>
  <dt>{d.term}</dt>
  <dd>{d.definition}</dd>
</>

The most important case will be for rendering td element in tr (a TR component). If we don't, then we're breaking the rule of HTML. The component will not be rendered properly. In react, it will throw you an error.

Update2:

Also, if you have long list of props like below:

const {
  items,
  id,
  imdbID,
  title,
  poster,
  getMovieInfo,
  addToFavorites,
  isOpen,
  toggleModal,
  closeModal,
  modalData,
} = props

You may consider destructuring like:

const { items, ...other } = props
// and in your component you can use like:
<div modalData={other.modalData}>

But, personally I prefer using first example code. It's because while developing I won't need to look back to other component or look for the console each and every time. In the given example there's key like modalData={} so we easily maintain modalData={other.modalData}. But what if it is needed to code like <div>{modalData}</div>? Then, you may also agree with my preference.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...