You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React可排序表格无法排序:新手开发者技术求助

Fixing Your React Sortable Table Issue

Hey there! Let's get that sortable table up and running. It sounds like when you stripped down the Codepen example, you might have left out some critical pieces needed for sorting—like tracking the current sort state, handling header clicks, and the actual sorting logic. Let's fix this step by step.

First, let's outline the key components you're missing:

  • State to track sort settings: We need to know which column is being sorted and whether it's ascending or descending.
  • A handler for header clicks: This will update our sort state when a user clicks a column header.
  • Sorted data rendering: We'll modify your data generation to return data sorted based on the current state.

Here's a complete, fixed version of your component with explanations:

class PlayerRankings extends React.Component {
  constructor(props) {
    super(props);
    // Add state to track sort configuration
    this.state = {
      sortKey: 'rank', // Default sort column
      sortDirection: 'asc' // Default sort direction
    };
    // Bind the handler to ensure correct `this` context
    this.handleSort = this.handleSort.bind(this);
  }

  // Handler for header clicks - updates sort state
  handleSort(sortKey) {
    // If clicking the same column, toggle direction; else set to ascending
    const newDirection = this.state.sortKey === sortKey 
      ? (this.state.sortDirection === 'asc' ? 'desc' : 'asc')
      : 'asc';
    
    this.setState({
      sortKey,
      sortDirection: newDirection
    });
  }

  generateRankData() {
    const data = [
      {rank: 1, week: 3, month: 2, player: "Steph", pos: "PG", team: "Warriors", war: 6, ws: 5.2},
      {rank: 2, week: -1, month: -1, player: "Lebron", pos: "SF", team: "Lakers", war: 5.8, ws: 4.9},
      {rank: 3, week: 2, month: 1, player: "Giannis", pos: "PF", team: "Bucks", war: 5.5, ws: 4.7}
      // Add your remaining data here
    ];

    // Sort the data based on current state
    const { sortKey, sortDirection } = this.state;
    return [...data].sort((a, b) => {
      // Handle numeric vs string sorting
      if (typeof a[sortKey] === 'number') {
        return sortDirection === 'asc' ? a[sortKey] - b[sortKey] : b[sortKey] - a[sortKey];
      } else {
        return sortDirection === 'asc' 
          ? a[sortKey].localeCompare(b[sortKey])
          : b[sortKey].localeCompare(a[sortKey]);
      }
    });
  }

  render() {
    const sortedData = this.generateRankData();
    const { sortKey, sortDirection } = this.state;

    return (
      <table>
        <thead>
          <tr>
            {/* Add onClick handlers to each header, pass the column key */}
            <th onClick={() => this.handleSort('rank')}>
              Rank {sortKey === 'rank' && (sortDirection === 'asc' ? '↑' : '↓')}
            </th>
            <th onClick={() => this.handleSort('player')}>
              Player {sortKey === 'player' && (sortDirection === 'asc' ? '↑' : '↓')}
            </th>
            <th onClick={() => this.handleSort('pos')}>
              Pos {sortKey === 'pos' && (sortDirection === 'asc' ? '↑' : '↓')}
            </th>
            <th onClick={() => this.handleSort('team')}>
              Team {sortKey === 'team' && (sortDirection === 'asc' ? '↑' : '↓')}
            </th>
            <th onClick={() => this.handleSort('war')}>
              WAR {sortKey === 'war' && (sortDirection === 'asc' ? '↑' : '↓')}
            </th>
            <th onClick={() => this.handleSort('ws')}>
              WS {sortKey === 'ws' && (sortDirection === 'asc' ? '↑' : '↓')}
            </th>
          </tr>
        </thead>
        <tbody>
          {/* Map over sorted data to render rows */}
          {sortedData.map((player, index) => (
            <tr key={index}>
              <td>{player.rank}</td>
              <td>{player.player}</td>
              <td>{player.pos}</td>
              <td>{player.team}</td>
              <td>{player.war}</td>
              <td>{player.ws}</td>
            </tr>
          ))}
        </tbody>
      </table>
    );
  }
}

// Render the component
ReactDOM.render(<PlayerRankings />, document.getElementById('root'));

Let's break down what we added:

  1. State initialization: We set up sortKey (which column we're sorting by) and sortDirection (ascending/descending) in the constructor.
  2. handleSort function: This function updates the state when a header is clicked. If it's the same column as before, it toggles the sort direction; otherwise, it defaults to ascending.
  3. Sorted data in generateRankData: We create a copy of the original data (so we don't mutate the original) and sort it based on the current state—handling both numeric and string values correctly.
  4. Clickable headers: Each header has an onClick handler that calls handleSort with the corresponding column key. We also add an arrow (↑/↓) to indicate the current sort direction for the active column.
  5. Render sorted rows: We map over the sorted data instead of the raw data to display rows in the correct order.

This should get your table sorting properly. Feel free to adjust the columns or add more data as needed!

内容的提问来源于stack exchange,提问作者Canovice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:11:57