首页 > 解决方案 > 如何在使用打字稿进行排序时解决类型错误?

问题描述

我正在尝试使用通过 API 检索的列表对表进行排序。我在 react + typescript 中这样做。我正面临类型错误。请帮助我。下面是我的代码。因此,通过将鼠标悬停在 Name 、 Type 、 Color 这应该排序但排序不起作用。请仔细阅读代码并帮助我进行排序。



export interface VehicleListProps {
    vehicle: VehicleState;

    listVehicles: (limit: number, skip: number) => void;
    addVehicle: (id: string) => void;
    deleteVehicle: (id: string, limit: number, skip: number) => void;
}

const Row = ({name, type , color }) => (
  <div className="row">
    <div>{name}</div>
    <div>{type}</div>
    <div>{color}</div>

  </div>
);

const VehicleList: React.FC<VehicleListProps> = (props) => {

    constructor(props); {
      this.state = {
        data: vehicle

};


     this.compareBy = compareBy.bind(this);
     this.sortBy = sortBy.bind(this);
    }

    function compareBy(key) {
      return function (a, b) {
        if (a[key] < b[key]) return -1;
        if (a[key] > b[key]) return 1;
        return 0;
      };
    }

  function  sortBy(key) {
      let vehicle = [...this.state.data];
      vehicle.sort(this.compareBy(key));
      this.setState({data: vehicle});
    }

    const rows = this.state.data.map( (rowData) => <Row {...rowData} />);

    return (

        <div>  

          <div className="row gap-20 masonry pos-r">
              <Table id="dataTable" className="table table-hover table-striped">
                  <thead className="thead-dark" >
                      <tr>
                          <th onClick={() => this.sortBy('name')}>Name</th>
                          <th onClick={() => this.sortBy('type')}>Type</th>                     
                          <th onClick={() => this.sortBy('color')}>Color</th>         
                          <th></th>
                      </tr>
                  </thead>
                  <tbody>{
                      vehicle.page.collection.map((vehicle, idx) => {
                          return (
                              <tr key={idx}>
                                  <td><a className="vehicleName" href={`/vehicles/${vehicle.id}`}>{vehicle.name}</a></td>
                                  <td>{vehicle.type}</td>

                                  <td>{vehicle.color}</td>

                              </tr>
                          )
                      })
                  }</tbody>

              </Table>


              </div>

          </div>
        </div>
    );
}

标签: reactjstypeerrortypescript1.8tablesort

解决方案


推荐阅读