我在每次渲染后都无法让表格自动排序时遇到麻烦

时间:2019-04-11 06:43:50

标签: javascript reactjs

这是我的第一个React应用程序,所以问题可能只是我不知道要在网上搜索什么才能找到最佳答案,反正,这就是:

以下是我到目前为止使用的表格的链接:https://student.labranet.jamk.fi/~L8314/reactapp/

codepen

选择一个火车站,例如赫尔辛基或坦佩雷,然后单击提交。

数据是通过一些大型API呈现的,并且仅显示在该特定车站停止的火车。

请注意,默认情况下,火车按第一列中的数字排序。

问题在于,默认情况下,应始终按每次渲染的时间对其进行排序。

已接近完成,您可以单击“到达”按钮,“离开”按钮,也可以单击“时间”列,它将按时间排序。

我尝试过的一些方法是,如果我在Submit按钮中有sort方法,它将首先对表进行排序,然后从API返回到默认顺序后将其呈现。如果将sort方法放在handlesubmit或其他函数的末尾,则根本不会调用它。

所以基本上我的问题是,如何在任何渲染后自动调用函数排序(或者说A)?

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      stations: [],
      liveTrains: [],
      thisVersionNumber: 0,
      sort: {
      column: null,
      },
      value: "",
      thisStationCode: "",
      arrivaltime: "300",
      departuretime: "0",
      arriving: "10",
      departing: "0"
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.getStationName = this.getStationName.bind(this);
    this.getArrivals = this.getArrivals.bind(this);
    this.getDepartures = this.getDepartures.bind(this);
    this.onSort = this.onSort.bind(this);
    this.getTrainNumber = this.getTrainNumber.bind(this);
  }
  handleChange(event) {
    this.setState({ value: event.target.value });
  }
  
  handleSubmit(event) {
    let currentStation = this.state.stations.filter(
      station => station.stationName === this.state.value
    );
    this.setState({ thisStationCode: currentStation[0].stationShortCode, thisVersionNumber: currentStation[0].version });
    fetch("https://rata.digitraffic.fi/api/v1/live-trains/station/" + currentStation[0].stationShortCode + "?version=1&arrived_trains=0&arriving_trains=" + this.state.arriving + "&departed_trains=0&departing_trains=" + this.state.departing + "&minutes_before_departure=" + this.state.departuretime + "&minutes_after_departure=0&minutes_before_arrival=" + this.state.arrivaltime + "&minutes_after_arrival=0&include_nonstopping=false"
    )
      .then(res => res.json())
      .then(data =>
        this.setState({
          liveTrains: data
        })
      )
      
      .catch(error => this.setState({ error, isLoaded: false }));
    event.preventDefault();
    
  }

  componentDidMount() {
    this.fetchStations();
    this.onSort('sortTrains',this.state.thisStationCode)
  }

  fetchStations() {
    fetch("https://rata.digitraffic.fi/api/v1/metadata/stations")
      .then(res => res.json())
      .then(data =>
        this.setState({
          stations: data,
          isLoaded: true
        })
      )
      .catch(error => this.setState({ error, isLoaded: false }));
  }
  getTrainType = (traincat, commID, trainnum) => {
    var thisTraintype = this.state.liveTrains.filter(
      train =>
        traincat === train.trainCategory &&
        commID === train.commuterLineID &&
        trainnum === train.trainNumber
    );
    //console.log(thisTraintype[0])
    for (var i = 0; i < thisTraintype.length; i++) {
      //console.log(thisTraintype[i].commuterLineID)
      //console.log(commID)
      //console.log(thisTraintype[i].trainNumber)
      //console.log(trainnum)
      if (
        thisTraintype[i].trainNumber === trainnum &&
        thisTraintype[i].commuterLineID === ""
      ) {
        return thisTraintype[i].trainType + thisTraintype[i].trainNumber;
      } else {
        return (
          thisTraintype[i].trainCategory +
          " train " +
          thisTraintype[i].commuterLineID
        );
      }
    }
  };
  getTrainNumber = (versionnum) => {
    var thisTraintype = this.state.liveTrains.filter(
      train =>
        versionnum === train.version
    );
    for (var i = 0; i < thisTraintype.length; i++) {
      if (
        thisTraintype[i].version === versionnum
      ) {
        return thisTraintype[i].trainNumber;
      } 
    }
  };
  getStationName = shortcode => {
    let newstation = this.state.stations.filter(
      station => station.stationShortCode === shortcode
    );
    return newstation[0].stationName;
  };
  getScheduledTime = (thisCode, traintype, trainnumber, trainData) => {
    const sortedliveTrains = []
    var thisTrain = trainData.filter(
      train => trainnumber === train.trainNumber && traintype === train.trainType
    );
    //console.log(thisTrain,thisCode,traintype,trainnumber)
    for (var i = 0; i < thisTrain[0].timeTableRows.length; i++) {
      //console.log(thisTrain[i].timeTableRows.length)
      if (thisTrain[0].timeTableRows[i].stationShortCode === thisCode) {
        //console.log(thisTrain[0].timeTableRows[i].scheduledTime)
        var date = new Date(thisTrain[0].timeTableRows[i].scheduledTime);
        var result = date.toLocaleString("en-GB", {
          timeZone: "Europe/Helsinki",
          //year: 'numeric',
          //month: 'short',
          //day: 'numeric',
          hour: "2-digit",
          minute: "numeric",
          //second: 'numeric',
          hour12: false
        });
          
          sortedliveTrains.push({result})
          //console.log(sortedliveTrains[0].result)
          //console.log(sortedliveTrains)
          return sortedliveTrains[0].result
        
        
      }
    }
        
      
        
  };
  getArrivals() {
    this.setState({
      arrivaltime: "300",
      departuretime: "0",
      arriving: "10",
      departing: "0",
      sort: this.onSort('sortTrains',this.state.thisStationCode)
    })
    this.onSort('sortTrains',this.state.thisStationCode)
  }
  getDepartures() {
    this.setState({
      arrivaltime: "0",
      departuretime: "300",
      arriving: "0",
      departing: "10",
      sort: this.onSort('sortTrains',this.state.thisStationCode)
    })
    this.onSort('sortTrains',this.state.thisStationCode)
  }
  onSort = (column, versionnum) => (e) => { //var date = new Date(thisTrain[0].timeTableRows[i].scheduledTime);
    const direction = 'asc'
    const sortedData = this.state.liveTrains.sort((a, b) => {
      var sortA = a.timeTableRows.filter( train => 
        versionnum === train.stationShortCode
      );
      var sortB = b.timeTableRows.filter( train => 
        versionnum === train.stationShortCode
      );
      if (column === 'sortTrains') {
        const nameA = new Date(sortA[0].scheduledTime).getTime()
        const nameB = new Date(sortB[0].scheduledTime).getTime()
        if (nameA < nameB) {
          return -1;
        }
        if (nameA > nameB) {
          return 1;
        }

        // names must be equal
        return 0;
      }
    });
    
    
    this.setState({
      data: sortedData,
      sort: {
        column,
        direction,
      }
    });
  };
  
    render() {
    const { error, isLoaded, stations } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div>
          <form id="form" onSubmit={this.handleSubmit}>
            <input
              type="text"
              id="stationList"
              list="station-list"
              name="stations"
              onChange={this.handleChange}
            />
            <datalist id="station-list">
              <select id="selectStation" value={this.state.value}>
                {stations.map(station => (
                  <option
                    key={station.stationName}
                    value={station.stationName}
                    onChange={this.HandleChange}
                  >
                    {station.stationShortCode}
                  </option>
                ))}
              </select>
            </datalist>
            <input type="submit" id="btn" value="submit" /><br></br>
            <input type="submit" onClick={this.getArrivals}  value="Arrivals" /><input type="submit" onClick={this.getDepartures} value="Departures" />
          </form>

          <table id="Schedules" ref="Schedules">
        <thead>
          <tr>
            <th>Train</th>
            <th>Departure Station</th>
            <th>Arrival Station</th>
            <th id="sortthis" onClick={this.onSort('sortTrains',this.state.thisStationCode)}>Time</th>
          </tr>
        </thead>
        <tbody>
          {this.state.liveTrains.map(train => (
      <tr key={train.trainNumber}>
            <td>
              {this.getTrainType(
                train.trainCategory,
                train.commuterLineID,
                train.trainNumber
              )}
            </td>
            <td>
              {this.getStationName(
                train.timeTableRows[0].stationShortCode
              )}
            </td>
            <td>
              {this.getStationName(
                train.timeTableRows[train.timeTableRows.length - 1]
                  .stationShortCode
              )}
            </td>
            <td>
              {this.getScheduledTime(
                this.state.thisStationCode,
                train.trainType,
                train.trainNumber,
                this.state.liveTrains
              )}
            </td>
          </tr>
          ))}
    </tbody>
      </table>

        </div>
      );
    }
  }
  }
ReactDOM.render(
    <MyComponent />,
    document.getElementById('main')
);
#sortthis {cursor: pointer;} //mouseover Time column
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.4.2/react-dom.min.js"></script>
<!doctype html>

<html lang="en">

<head>
    <meta charset="utf-8">

    <title>VR API</title>
    <meta name="description" content="VR API">
    <meta name="author" content="Corey Johnson">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>


</head>

<body>
    <div id="main">
    </div>
<script>

</script>
</body>

</html>

0 个答案:

没有答案