Как отсортировать данные таблицы по asc и dsc? - PullRequest
0 голосов
/ 31 октября 2019

Я пытаюсь отсортировать данные из данных в таблице, и я написал некоторый код, но я не могу отсортировать таблицу, просто показывает значок, не работающий сортировку.

Вот мой код, который я написал, поэтому, пожалуйста, посмотрите и объясните мне, что я должен улучшить, чтобы он работал. Я не знаю, где в этом коде ошибка, из-за которой я не могу отсортировать данные, и я также пытался использовать данные jQuery, но когда я использовал данные в формате json, данные не работают. Спасибо

import React, { Component } from "react";
import Form from "../Form";
import Header1 from "../../Components/Layout/Header1";
import Search from "../Cars/Search";
import Summary from "./Summary";
import "./index";

const sortTypes = {
  up: {
    class: "sort-up",
    fn: (a, b) => a.net_worth - b.net_worth
  },
  down: {
    class: "sort-down",
    fn: (a, b) => b.net_worth - a.net_worth
  },
  default: {
    class: "sort",
    fn: (a, b) => a
  }
};

class Driver extends Component {
  constructor(props) {
    super(props);
    this.state = {
      walk: [],
      currentSort: "default"
    };
    this.onSortChange = this.onSortChange.bind(this);
  }

  onSortChange = () => {
    const { currentSort } = this.state;
    let nextSort;

    if (currentSort === "down") nextSort = "up";
    else if (currentSort === "up") nextSort = "default";
    else if (currentSort === "default") nextSort = "down";

    this.setState({
      currentSort: nextSort
    });
  };

  async componentDidMount() {
    try {
      const res = await fetch(`http://softbike.dev.myddp.eu/api/1/walk/`);
      const walk = await res.json();
      console.log(walk);
      this.setState({
        walk
      });
    } catch (e) {
      console.log(e);
    }
  }

  render() {
    const { currentSort } = this.state;
    return (
      <div className="container" style={{ marginTop: "20px" }}>
        <div className="row">
          <div className="col-sm-8">
            <Form loaddata={this.getData} />
          </div>
        </div>
        <Header1 />

        <div className="headerr">
          <Search />
          <table
            // id="example"
            className="table table-hover"
            style={{ width: "100%" }}
          >
            <thead style={{ position: "relative" }}>
              <tr className="th">
                <th>Id</th>
                <th>Name</th>
                <th className="t">
                  No. car <br></br>
                  switching &nbsp;
                  <i
                    onClick={this.onSortChange}
                    className={`fas fa-${sortTypes[currentSort].class}`}
                  />
                </th>
                <th>
                  Mileage[km] &nbsp;
                  <i
                    onClick={this.onSortChange}
                    className={`fas fa-${sortTypes[currentSort].class}`}
                  />
                </th>
                <th className="t">
                  Fuel <br></br> Consumed[L] &nbsp;
                  <i
                    onClick={this.onSortChange}
                    className={`fas fa-${sortTypes[currentSort].class}`}
                  />
                </th>
                <th className="t">
                  Average Fuel <br></br> Consumed[L/100km] &nbsp;
                  <i
                    onClick={this.onSortChange}
                    className={`fas fa-${sortTypes[currentSort].class}`}
                  />
                </th>
                <th className="t">
                  Overspeeding <br></br> Distance[%] &nbsp;
                  <i
                    onClick={this.onSortChange}
                    className={`fas fa-${sortTypes[currentSort].class}`}
                  />
                </th>
                <th className="t">
                  No. critical <br></br> Overspeeding &nbsp;
                  <i
                    onClick={this.onSortChange}
                    className={`fas fa-${sortTypes[currentSort].class}`}
                  />
                </th>
                <th className="t">
                  <span
                    id="dropdownMenuLink"
                    role="button"
                    className="dropdown-toggle"
                    data-toggle="dropdown"
                    aria-haspopup="true"
                    aria-expanded="false"
                    //
                  >
                    Overall <br></br> Score
                  </span>
                  <div
                    className="dropdown-menu nott "
                    aria-labelledby="dropdownMenuLink"
                    style={{ position: "relative", zIndex: "9999999" }}
                  >
                    <a className="dropdown-item" href="# ">
                      Action
                    </a>
                    <a className="dropdown-item" href="/dashboard ">
                      dashboard
                    </a>
                    <a className="dropdown-item" href="# ">
                      Something else here
                    </a>
                  </div>
                  &nbsp; &nbsp;
                  <i
                    onClick={this.onSortChange}
                    className={`fas fa-${sortTypes[currentSort].class}`}
                  />
                </th>
              </tr>
            </thead>

            {this.state.walk.sort(sortTypes[currentSort].fn).map(c => (
              <tbody key={c.pk}>
                <tr>
                  <td scope="row">{c.pk}</td>
                  <td>
                    <a
                      href="/doverview"
                      style={{ color: "#b71c1c" }}
                      class="font-weight-bold"
                    >
                      {c.user}{" "}
                    </a>
                  </td>
                  <td>{c.total_milage ? `${c.total_milage}` : 0} </td>
                  <td>{c.total_movingtime ? `${c.total_movingtime}` : 0} </td>
                  <td>{c.total_letter ? `${c.total_letter}` : 0}</td>
                  <td>
                    {c.total_letters_weight ? `${c.total_letters_weight}` : 0}{" "}
                  </td>
                  <td>{c.total_pack ? `${c.total_pack}` : 0}</td>
                  <td>
                    {c.total_packages_weight ? `${c.total_packages_weight}` : 0}
                  </td>
                  <td>{c.total_deliveries ? `${c.total_deliveries}` : 0}</td>
                </tr>
              </tbody>
            ))}
            <Summary />
          </table>
        </div>
      </div>
    );
  }
}

export default Driver;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...