簡體   English   中英

React / nextJS:如何在間隔內重新加載api數據

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

我試圖構建一個react組件(在我的nextJS應用程序中),該組件每三秒鍾重新加載一些數據。 數據來自一個api,該API返回一個json,例如{ humidity: 69.98, temperature: 23.45 }

我想這不是必須要做的,不是嗎? 此外,它不是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

這應該可以工作,不需要getInitialProps 如果一開始需要數據,則可以執行以下操作:

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