gpt4 book ai didi

javascript - react /nextJS : How to reload api data in interval

转载 作者:行者123 更新时间:2023-12-03 00:58:27 25 4
gpt4 key购买 nike

我尝试构建一个 react 组件(在我的 nextJS 应用程序中),它每三秒重新加载一些数据。数据来自 api,它返回类似 {湿度:69.98,温度:23.45 } 的 json。

我想这不是必须要做的事情,不是吗?此外,它不是 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();
}

关于javascript - react /nextJS : How to reload api data in interval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52719384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com