简体   繁体   English

React / nextJS:如何在间隔内重新加载api数据

[英]React/nextJS: How to reload api data in interval

I've tried to build an react component (in my nextJS app) which reloads some data every three seconds. 我试图构建一个react组件(在我的nextJS应用程序中),该组件每三秒钟重新加载一些数据。 The data comes from an api, which returns a json like { humidity: 69.98, temperature: 23.45 } . 数据来自一个api,该API返回一个json,例如{ humidity: 69.98, temperature: 23.45 }

I guess this is not how it has to be done, isn't it? 我想这不是必须要做的,不是吗? Furthermore it is not a DRY code :-( 此外,它不是DRY代码:-(

import React, { Component } from 'react'
import fetch from 'isomorphic-unfetch'

class Index extends Component {
  static async getInitialProps () {
    const api = process.env.NODE_ENV === 'production'
      ? 'http://172.17.0.2:3000/get-data'
      : 'http://localhost:3000/get-data'
    const res = await fetch(api)
    return res.json()
  }

  constructor (props) {
    super(props)
    const { temperature, humidity } = props
    this.state = {
      temperature,
      humidity
    }
  }

  componentDidMount () {
    this.interval = setInterval(
      async () => {
        const api = process.env.NODE_ENV === 'production'
          ? 'http://172.17.0.2:3000/get-data'
          : 'http://localhost:3000/get-data'
        const res = await fetch(api)
        const data = await res.json()
        this.setState(data)
      }, 3000)
  }

  componentWillUnmount () {
    clearInterval(this.interval)
  }

  render () {
    const { humidity, temperature } = this.state

    return (
      <div>
        <div>
          {humidity} %
        </div>
        <div>
          {temperature}° C
        </div>
      </div>
    )
  }
}

export default Index

This should work, no need to have getInitialProps . 这应该可以工作,不需要getInitialProps If you need data at start, you can do: 如果一开始需要数据,则可以执行以下操作:

async fetchData = () => {
    const api = process.env.NODE_ENV === 'production'
      ? 'http://172.17.0.2:3000/get-data'
      : 'http://localhost:3000/get-data'
    const res = await fetch(api)
    const data = await res.json()
    this.setState(data)
} 

componentDidMount () {
    this.interval = setInterval(this.fetchData, 3000)
    this.fetchData();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM