在React中迭代数据数组时渲染JSX元素的最有效方法 [英] Most efficient way of rendering JSX elements when iterating on array of data in React

查看:174
本文介绍了在React中迭代数据数组时渲染JSX元素的最有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含对象的数组。我正在创建此数组的映射,以使用 span 组件呈现名称。

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"}];

我一直在使用以下两种不同的功能来迭代该对象数组,并使用map to渲染JSX元素。

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

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;



功能2:



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;

我知道以上两种不同的使用方式 map 并渲染JSX元素。除了这两个之外,还有其他方法可以做同样的事吗?如果是这样,建议使用哪一个?

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?

推荐答案

大多数情况下,我遵循这条规则:

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
}

钩住RenderItems

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>
    )
  }
}

附加组件中的数据

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.

此外,我不会创建 id 仅用于使用密钥:

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.

如果你想避免使用不必要的html标签,你可以使用 React.Fragment

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} />

注意:


  1. 您可以使用<>< /> 作为< React.Fragment>的别名;< /React.Fragment> 仅当您没有任何其他财产时。由于我们正在使用关键属性,而不是使用它。

  2. 看看 this 以支持 React.Fragment的简短表示法

  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.

使用<>< />

<>{d.name}</>

这将呈现 d.name '没有任何标记的html值。当我们专门改造现有设计以应对应用时,这被认为是最好的。或者,可能还有其他情况。比如,我们将显示一个定义列表:

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>

我们不想附加不必要的html标签,然后使用Fragment会让我们的生活更轻松:

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

示例:

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

最重要的情况是渲染 td tr 中的元素(TR组件)。如果我们不这样做,那么我们就违反了HTML的规则。组件将无法正确呈现。在反应中,它会给你一个错误。

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.

另外,如果你有长长的道具列表如下:

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

您可以考虑解构如:

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

但是,我个人更喜欢使用第一个示例代码。这是因为在开发过程中我不需要回顾其他组件或者每次都寻找控制台。在给定的示例中,有像 modalData = {} 这样的键,所以我们很容易维护 modalData = {other.modalData} 。但是,如果需要代码如< div> {modalData}< / div> ?然后,您也可能同意我的偏好。

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.

这篇关于在React中迭代数据数组时渲染JSX元素的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆