React:给定一个数组,有效地以相反的顺序渲染元素 [英] React: Given an array, render the elements in reverse order efficiently

查看:844
本文介绍了React:给定一个数组,有效地以相反的顺序渲染元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前以典型的React风格呈现一个列表。该列表作为数组道具传递,我像这样映射:

I currently render a list in the typical React-style. The list is passed as an array prop, and I map over it like so:

{this.props.myList.map(createListItem, this)}

因此,当添加新元素时,它看起来像是添加了最新项目到列表的末尾。

So when a new element is added, it appears like the latest item was added to the end of the list.

我想要它,所以最新项目出现在顶部。即所有内容都按逆时间顺序排列。

I would like it so the latest item appears at the top. i.e. everything appears in reverse-chronological order.

到目前为止我提出的两个选项是:
1)反转列表,创建一个新的每次添加某些内容时都会生成数组,并将此反转列表作为道具传递。
2)使用班次。

The two options I've come up with so far are: 1) Reverse the list, creating a new array each time something is added, and pass this reversed list as the prop. 2) Use shift.

但由于表现,它们都没有吸引力。

But they're both unappealing because of performance.

I我不知道Javascript支持相反顺序的映射。我一直在尝试for循环,但我无法让它工作。

I'm not aware of Javascript supporting mapping in reverse order. I've been trying a for-loop but I haven't been able to get it to work.

以相反顺序渲染数组的惯用方法是什么React?

What is the idiomatic way to render an array in reverse order in React?

推荐答案

如果您选择使用 reverse()反转列表 shift() splice(),你应首先制作数组的浅表副本,然后再使用副本上的那个功能。不应该改变React中的道具。

If you choose to reverse the list using reverse(), shift() or splice(), you should make a shallow copy of the array first, and then use that function on the copy. Props in React should not be mutated.

例如:

[...this.props.myList].reverse().map(createListItem, this)

this.props.myList.slice(0).map(createListItem, this)

(这应该是一个评论,但我还没有分数这样做:))

(this should really be a comment, but I don't have the points to do that yet :))

这篇关于React:给定一个数组,有效地以相反的顺序渲染元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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