How can I return values once per second using react and axios?

柔情痞子 提交于 2019-12-13 03:43:18

问题


I'm trying to make a site that grabs data from a server with axios, then updates the final content once per second.

Here's the ajax request.

axiosFunc = () => {

    axios.get('https://api.warframestat.us/pc').then(results => {
      this.setState({
        alerts: results.data.alerts
      });
      setTimeout(this.axiosFunc,1000 * 60);
    })
  }
  componentDidMount() {
    this.axiosFunc();
  }

Then I return conditionally rendered components (AlertsBox) with data passed into it. They render based by time of day compared to time that they start and end.

  render() {
    return (
      <main className="content">
        <header>{this.state.whichEvent.toUpperCase()}</header>

    {this.state.alerts.map(alert => {
      let enddate = alert.expiry.substring(0,10);
      let endtime = alert.expiry.substring(11,19);

      let startdate = alert.activation.substring(0,10);
      let starttime = alert.activation.substring(11,19);

      let endAlert = new Date(`${enddate} ${endtime} UTC`).toLocaleString();

      let startAlert = new Date(`${startdate} ${starttime} UTC`).toLocaleString();

      let endNumber = Date.parse(endAlert);
      let startNumber = Date.parse(startAlert);

      return Date.now() > startNumber && Date.now() < endNumber ?
        <AlertsBox
          deadline={endAlert}
          activate={startAlert}
          timeOne={enddate}
          timeTwo={endtime}
          timeThree={startdate}
          timeFour={starttime}
          image={alert.mission.reward.thumbnail}
          reward={alert.mission.reward.itemString}
          credits={alert.mission.reward.credits}
          type={alert.mission.type}
          sector={alert.mission.node}
          key={alert.id}/>
          :null
    })}
  </main>
);
}

Next, in the component, I create a timer function to display time once.

let timer = () => {
  //Extract the data from the original string
  //Convert the UTC to locale time

  let seconds = Math.round((this.state.eta/1000) % 60);
  let minutes = Math.floor( (this.state.eta/1000/60) % 60 );
  let hours = Math.floor( (this.state.eta/(1000*60*60)) % 24 );
  let days = Math.floor( this.state.eta/(1000*60*60*24) );

  return `${days >= 1? days + " days" : ""} ${hours >= 1? hours + " hrs" : ""} ${minutes} min ${seconds} sec`
}

Finally, within the render area, I render the return function

<figcaption>

   {timer()}

</figcaption>

This renders it once. If I do this...

{setInterval(timer(), 1000)}

The function doesn't work, and gives the wrong values. How do I make it give the right values?

来源:https://stackoverflow.com/questions/48368719/how-can-i-return-values-once-per-second-using-react-and-axios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!