【问题标题】:How to sort HTML Table in ReactJS如何在 ReactJS 中对 HTML 表进行排序
【发布时间】:2017-12-31 18:08:55
【问题描述】:

我有arrayObjects,我将我的数据添加到HTML Table。现在我需要按版本对数据进行排序。我怎样才能在React 中做类似的事情?

  render() {
    return (
      <div>
        <div>
          <Label> We got {this.state.count} elements in our database. </Label>
        </div>
        <div>
          <Table hover striped bordered responsive size="sm" >
            <thead>
              <tr>
                <th>VERSION</th>
                <th>DATE</th>
                <th>UUID</th>
              </tr>
            </thead>
            <tbody>
              {this.state.results.map(result =>
                <tr key={result.fileId}>
                  <td>{result.VERSION}</td>
                  <td>{result.ORIGIN}</td>
                  <td>{result.UUID}</td>
                </tr>
              )}
            </tbody>
          </Table>
        </div>
      </div>
    );
  }
}

也许我可以使用一些js 脚本,但请告诉我如何使用它,我是ReactJS 的新手。例如,我的版本是0.26.8

【问题讨论】:

    标签: html reactjs reactstrap


    【解决方案1】:

    我会在这里使用 lodash 的 sortBy() 函数:

    https://lodash.com/docs/4.17.4#sortBy

    const sorted = _.sortBy(this.state.results, 'VERSION')
    

    然后映射到sorted 而不是this.state.results

    【讨论】:

      【解决方案2】:

      只需确保this.state.results 在渲染前正确排序


      最简单的方法可能类似于以下内容:

        {this.state.results.sort((a, b) => a.VERSION - b.VERSION).map(result =>
          <tr key={result.fileId}>
            <td>{result.VERSION}</td>
            <td>{result.ORIGIN}</td>
            <td>{result.UUID}</td>
          </tr>
        )}
      

      编辑:由于您声明版本不是数值,而是semantic versioning 字符串,因此您的排序函数需要更复杂一些。我建议您查看 this SO question,或使用 one of the many available libraries 覆盖该用例。

      【讨论】:

      • 我的版本看起来像:0.22.6,不只是一个数字。我忘了把它添加到描述中。已经更新了,抱歉。
      【解决方案3】:
      const sorted = results.sort((x,y) => {
          return parseInt(x.VERSION) - parseInt(y.VERSION);
      });
      

      升序排列

      【讨论】:

      • 我的版本看起来像:0.22.6,不只是一个数字。我忘了把它添加到描述中。已经更新了,抱歉。
      猜你喜欢
      • 2019-08-31
      • 2021-08-27
      • 1970-01-01
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 2012-07-22
      相关资源
      最近更新 更多