【问题标题】:React JS Sorting and updating ArrayReact JS 排序和更新数组
【发布时间】:2020-06-22 21:27:26
【问题描述】:

我有一个处理菜单数组排序的函数,但我不确定如何正确编码。我可能会错过像地图这样的东西,但我不确定。单击按钮时,它应该更新状态并按字母顺序呈现菜单。当我单击按钮时,我下面的代码也不会导致任何内容呈现。另外,我将如何正确地将 fetchMenus 实现到 handleMenuSort 函数中以填充数组?

编辑

class MenuFilter extends Component {
  constructor() {
  super(); 
  this.state = { menus: [] };
}

handleMenuFetch = e => {
    this.props.fetchMenus()
};

handleMenuSort = e => {
  this.setState(state => {
      this.state.menus.sort(function(a, b) {
      if (a.name < b.name) {
        return -1;
      }
      if (a.name > b.name) {
        return 1;
      }

      return 0;
    })
  });
}

render() {
  return (
    <Container>
        <Row>
          <div>
              <button id="menu-show-button" onClick={this.handleMenuFetch}>Show Menus</button>
          </div>
          <div>
              <button id="sort-button" onClick={this.handleMenuSort}>Sort Menus</button>
          </div>
        </Row>
    </Container>
    )
  }

【问题讨论】:

    标签: javascript arrays reactjs sorting react-redux


    【解决方案1】:

    问题是你正在改变状态。一种选择是使用扩展运算符制作菜单数组的浅表副本,然后对该数组进行排序。

    this.setState({
        menus: [...this.state.menus].sort(function(a, b) {
          if (a.name < b.name) {
            return -1;
          }
          if (a.name > b.name) {
            return 1;
          }
    
          return 0;
        })
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-20
      • 1970-01-01
      • 2019-08-03
      • 2013-11-11
      • 2021-07-07
      • 2018-01-25
      • 2019-07-15
      • 2017-11-16
      相关资源
      最近更新 更多