Мгновенное изменение данных в реагирующей таблице на основе таймера в ReactJs - PullRequest
0 голосов
/ 03 марта 2019

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

То, что я получил до сих пор, - это то, что я использую вызов API для получения данных с моего сервера SQL, а затем сохраняю эти данные в BTree с меткой времени в качестве ключа.и данные в качестве значения.Прошедшее время является состоянием, а BTrees - тоже состояниями.Я пробовал как BTree, так и Hashmaps, так как изначально думал, что моей проблемой является длительное время поиска в Hashmaps.

В настоящее время это не работает, и я считаю, что это так, потому что мой поиск и поиск недостаточно быстро, даже с BTree.Значение со временем = 0 отображается правильно, но все последующие рендеры не определены, я прикрепил снимок экрана к отладчику консоли ниже.Числа - это время в мс, неопределенное означает, что у меня нет ключей этого значения, я знаю это.Я просто не уверен, как их синхронизировать.

введите описание изображения здесь

У меня большой набор данных, поэтому я не уверен, как поступить.Моя реализация полностью вне базы или я на правильном пути?Есть ли стандартизированный способ сделать это?

Вот соответствующий код, пожалуйста, дайте мне знать, если есть что-то еще, что я должен указать.

startTimer() {
    this.setState({
      isOn: true,
      time: this.state.time,
      start: Date.now() - this.state.time
    })
    this.timer = setInterval(() => this.setState({
      time: Date.now() - this.state.start
    }), 1);
  }

  stopTimer() {
    this.setState({isOn: false})
    clearInterval(this.time)
  }

  resetTimer() {
    this.setState({time: 0, isOn: false})
  }

  handleSubmit = async e => {
    e.preventDefault();
    const response = await fetch('/api/world', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ post: this.state.post }),
    });
    const body = await response.text();

    this.setState({ responseToPost: body });
  };

  render() {
    let start = (this.state.time == 0) ?
      <button onClick={this.startTimer}>start</button> :
      null

    let stop = (this.state.time == 0 || !this.state.isOn) ?
      null :
      <button onClick={this.stopTimer}>stop</button>

    let resume = (this.state.time == 0 || this.state.isOn) ?
      null :
      <button onClick={this.startTimer}>resume</button>

    let reset = (this.state.time == 0 || this.state.isOn) ?
      null :
      <button onClick={this.resetTimer}>reset</button>


    //DEBUG HERE
    console.log(this.state.time)
    console.log()

    var data = [{
      name: 'beams',
      aid: beamID,
      bytes: '',
      bytes: this.state.beamTree.get(this.state.time)
    },{
      name: 'cruise',
      aid: cruiseID,
      bytes: '',
      bytes: this.state.cruiseMap.get(this.state.time)
    },{
      name: 'dash',
      aid: dashID,
      bytes: '',
      bytes: this.state.dashMap.get(this.state.time)
    },{
      name: 'radio',
      aid: radioID,
      bytes: '',
      bytes: this.state.radioMap.get(this.state.time)
    },{
      name: 'tc',
      aid: tcID,
      bytes: '',
      bytes: this.state.tcMap.get(this.state.time)
    }]

    return (
      <div className="App">
          <div className="Sidebar">
            <ReactTable
              style={{"minheight" : "100%"}}
              showPagination={false}
              data={data}    
            columns={columns}     
              pageSizeOptions= {[3,9]}
            />
        </div>      
        <div>
        <h3>timer: {this.state.time}</h3>
        {start}
        {resume}
        {stop}
        {reset}
        </div>  

1 Ответ

0 голосов
/ 04 марта 2019

Итак, на случай, если кто-нибудь из будущего прочтет это, я использую setInterval.Нужно работать, но вот мой App.js

class App extends Component {
  constructor(props){
    super(props)
    this.state = {
      response: '',
      get: '',
      post: '',
      responseToPost: '',
      responseToGet: '',
      data: {},
      message: '',
      beamMap: new HashMap(),
      cruiseMap: new HashMap(),
      dashMap: new HashMap(),
      radioMap: new HashMap(),
      tcMap: new HashMap(),
      time: 0,
      isOn: false,
      start: 0,
      end: 0,
      beamBytes: '',
      radioBytes: '',
      cruiseBytes: '',
      dashBytes: '',
      tcBytes: '',
      radioTick: 0,
      cruiseTick: 0,
      dashTick: 0,
      tcTick: 0,
      tick: 0
  }
  this.startCruiseInterval = this.startCruiseInterval.bind(this)
  this.startDashInterval = this.startDashInterval.bind(this)
  this.startTCInterval = this.startTCInterval.bind(this)
  this.startBeamInterval = this.startBeamInterval.bind(this)
  this.startRadioInterval = this.startRadioInterval.bind(this)
  this.startTimeInterval = this.startTimeInterval.bind(this)
  this.startTimer = this.startTimer.bind(this)
  this.stopTimer = this.stopTimer.bind(this)
  this.resetTimer = this.resetTimer.bind(this)
}

  //TODO
  //variable vehicle and session
  componentDidMount() {
    fetch('/session/1/1').then(
      response => response.json()
    ).then(
        json => {
        this.setState({data: json});
        var str = this.state.data

        //Store json data into the appropriate hashmap
        for(var i=0;str.length;i++){
          if(str[i].aid==beamID){
            beamHolder.set(parseInt(str[i].time),str[i].data)
            this.setState({beamMap: beamHolder})
          }else if(str[i].aid==cruiseID){
            cruiseHolder.set(parseInt(str[i].time),str[i].data)
            this.setState({cruiseMap: cruiseHolder})
          }else if(str[i].aid==dashID){
            dashHolder.set(parseInt(str[i].time),str[i].data)
            this.setState({dashMap: dashHolder})
          }else if(str[i].aid==radioID){
            radioHolder.set(parseInt(str[i].time),str[i].data)
            this.setState({radioMap: radioHolder})
          }else if(str[i].aid==tcID){
            tcHolder.set(parseInt(str[i].time),str[i].data)
            this.setState({tcMap: tcHolder})
          }
        }
      }
    );
  }

  startTimeInterval(){
    return this.setState({time: Date.now() - this.state.start})
  }

  startRadioInterval(){
    this.setState({radioBytes: this.state.radioMap.get(this.state.radioTick)})
    this.setState({radioTick: this.state.radioTick + 500})
  }

  startCruiseInterval(){
    this.setState({cruiseBytes: this.state.cruiseMap.get(this.state.cruiseTick)})
    this.setState({cruiseTick: this.state.cruiseTick + 500})
  }

  startDashInterval(){
    this.setState({dashBytes: this.state.dashMap.get(this.state.dashTick)})
    this.setState({dashTick: this.state.dashTick + 500})
  }

  startTCInterval(){
    this.setState({tcBytes: this.state.tcMap.get(this.state.tcTick)})
    this.setState({tcTick: this.state.tcTick + 500})
  }

  startBeamInterval(){
    this.setState({beamBytes: this.state.beamMap.get(this.state.tick)})
    this.setState({tick: this.state.tick + 500})
  }

  startTimer() {
    this.setState({
      isOn: true,
      time: this.state.time,
      start: Date.now() - this.state.time
    })

    this.timer = setInterval(this.startTimeInterval, 1)
    this.beamBytes = setInterval(this.startBeamInterval, 500)
    this.radioBytes = setInterval(this.startRadioInterval, 500)
    this.cruiseBytes = setInterval(this.startCruiseInterval, 500)
    this.dashBytes = setInterval(this.startDashInterval, 500)
    this.tcBytes = setInterval(this.startTCInterval, 500)
  }

  stopTimer() {
    this.setState({isOn: false})
    clearInterval(this.timer)
    clearInterval(this.beamBytes)
    clearInterval(this.radioBytes)
    clearInterval(this.cruiseBytes)
    clearInterval(this.dashBytes)
    clearInterval(this.tcBytes)
  }

  resetTimer() {
    this.setState({time: 0, isOn: false})
    this.setState({beamBytes:''})
    this.setState({radioBytes:''})
    this.setState({cruiseBytes:''})
    this.setState({dashBytes:''})
    this.setState({tcBytes:''})
    this.setState({tick:0})
    this.setState({radioTick:0})
    this.setState({cruiseTick:0})
    this.setState({dashTick:0})
    this.setState({tcTick:0})
  }

  render() {
    let start = (this.state.time == 0) ?
      <button onClick={this.startTimer}>start</button> :
      null

    let stop = (this.state.time == 0 || !this.state.isOn) ?
      null :
      <button onClick={this.stopTimer}>stop</button>

    let resume = (this.state.time == 0 || this.state.isOn) ?
      null :
      <button onClick={this.startTimer}>resume</button>

    let reset = (this.state.time == 0 || this.state.isOn) ?
      null :
      <button onClick={this.resetTimer}>reset</button>

    var data = [{
      name: 'beams',
      aid: beamID,
      bytes: this.state.beamBytes,
    },{
      name: 'cruise',
      aid: cruiseID,  
      bytes: this.state.cruiseBytes
    },{
      name: 'dash',
      aid: dashID,
      bytes: this.state.dashBytes
    },{
      name: 'radio',
      aid: radioID,
      bytes: this.state.radioBytes
    },{
      name: 'tc',
      aid: tcID,
      bytes: this.state.tcBytes
    }]

    return (
      <div className="App">
          <div className="Sidebar">
            <ReactTable
              style={{"minheight" : "100%"}}
              showPagination={false}
              data={data}    
            columns={columns}     
              pageSizeOptions= {[3,9]}
            />
        </div>      
        <div>
        <h3>timer: {this.state.time}</h3>
        {start}
        {resume}
        {stop}
        {reset}
        </div>  
      </div>
    );
  }
}

export default App;
...