Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - React: Given an array, render the elements in reverse order efficiently

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.

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'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.

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

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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.

For example:

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

or

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...