如何在 ReactJS 中排序 HTML Table

How to sort HTML Table in ReactJS

我有 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

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

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

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

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

只需确保 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 string, your sort function needs to be a bit more complex. I suggest you have a look at this SO question, or use one of the many available libraries

const sorted = results.sort((x,y) => {
    return parseInt(x.VERSION) - parseInt(y.VERSION);
});

升序排列