未排序的 table 数据与 table 中的已排序数据一起呈现

Unsorted table data is rendered along with sorted data in table

我正在使用 React 对 table 使用 underscore.js 进行排序,但排序后的数据会与原始数据一起添加到 table 的底部。我只需要在我的组件中渲染排序后的 table 。实现此目标的正确方法是什么?

 class Players extends React.Component {
   constructor() {
     super();
     this.state = { players:[]};
   }

   componentDidMount() {
     fetch('http://localhost:5000/players')
     .then((data) => data.json())
     .then((data) => this.setState( { players: data } ));
   }

   sortByCode = () => {
     this.setState( { "players": _.sortBy(this.state.players,'TEAMCODE')});
   }
 render() {
   return (
    <table border={1}>
      <tbody>
        <tr>
          <th onClick={this.sortByCode}>Code</th>
          <th>Name</th>
        </tr>
        {this.state.players.map( (item) => {
          return 
            <tr key={item.TEAMCODE}>
              <td><img height={20} width ={20} 
       alt="pics" src={'/logos/' + item.TEAMCODE + '_logo.svg'}></img> 
       </td>
              <td>{item.TEAMCODE}</td>
              <td>{item.NAME}</td></tr>;
        })}
        </tbody>
    </table>
 )};

不建议使用索引作为键(参见ReactJS documentation

我建议找到你的数据集的唯一键,它似乎是 TEAMCODE 和 NAME 的组合,所以你应该用以下代码替换你的代码:

<tr key={item.TEAMCODE+item.NAME}>