React:给定一个数组,有效地以相反的顺序渲染元素

时间:2016-06-06 18:04:21

标签: javascript reactjs

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

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

因此,当添加新元素时,似乎最新项目已添加到列表末尾。

我想要,所以最新的项目出现在顶部。即一切都按时间倒序排列。

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

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

我不知道Javascript支持相反顺序的映射。我一直在尝试循环,但我还没有能够让它发挥作用。

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

7 个答案:

答案 0 :(得分:9)

如果您需要在UI中以相反的顺序显示列表,也可以使用

flex-direction: row-reverse;

flex-direction: column-reverse;

答案 1 :(得分:5)

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

例如:

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

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

(这应该是一个评论,但我还没有要点:))

答案 2 :(得分:4)

正如其他人所指出的那样,卑微的反向方法在很大程度上起到了作用。我目前遇到了同样的问题,我必须说在Chrome中至少使用了array.reverse(),性能打击并没有被看到。在我看来,它比使用循环以相反的顺序对列表进行排序更好。

//...
public function calculate_shipping( $package ) {
    //...
$rate = array(
            'id' => $this->id,
            'label' => $this->title,
            'cost' => $cost //calculated based on the distance
        );
$this->add_rate( $rate );
}
//...

答案 3 :(得分:1)

使用flexDirection:'column-reverse'时状态发生变化时顺序会有所变化。我选择了function validBraces(braces){ let opening = [ '(', '[', '{'] let closing = [ ')', ']', '}'] let arr = [] //console.log(closing.indexOf(braces[")"]) === opening.indexOf(arr[")"])) for (let i = 0; i < braces.length; i++) { if (opening.includes(braces[i])) { arr.push(braces[i]) } else if (closing.indexOf(braces[i]) === opening.indexOf(arr[arr.length - 1])) { arr.pop() } else return false } return arr.length === 0; }可以很好地工作,而且您也不必弄乱数组数据。

答案 4 :(得分:0)

在数组的开头添加新元素:

array.splice(0,0,'value to add at beginning');

或使用立即调用的函数调用for循环:

{(() => {
     for(...) {
         return (<i>{whatever}</i>)
     }
})()}

答案 5 :(得分:0)

继续推动数组,渲染时,只需使用

即可
Array.reverse()

这里是documentation

提醒它会改变原来的

答案 6 :(得分:0)

使用mobx作为存储时,可以为反向数组创建computed属性,该属性将在原始observable array每次更改时重新评估和存储。

商店

import { observable, computed } from 'mobx';

class MyStore {
  @observable items = [1, 2, 3];

  @computed get itemsReversed() {
    return this.items.slice().reverse();
  }
}

export default MyStore;

渲染

import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';

@inject('myStore') @observer
class List extends Component {
  render() {
    const { myStore } = this.props;
    const { itemsReversed } = myStore;
    return (
      <div className="list">
        {itemsReversed.map(item => (
          <div className="list-item">{item}</div>
        ))}
      </div>
    );
  }
}

export default List;

根据官方文档,这是反转数组的首选方法:

与函数sortreverse的内置实现不同,observableArray.sort和reverse不会就地更改数组,而只会返回已排序/反向的副本。从MobX 5及更高版本开始,将显示警告。建议改用array.slice().sort()