Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript React/nextJS:如何在间隔内重新加载api数据_Javascript_Node.js_Asynchronous_Next.js - Fatal编程技术网

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

Javascript React/nextJS:如何在间隔内重新加载api数据,javascript,node.js,asynchronous,next.js,Javascript,Node.js,Asynchronous,Next.js,我尝试构建一个react组件(在我的nextJS应用程序中),它每三秒重新加载一些数据。数据来自一个api,它返回类似json的{湿度:69.98,温度:23.45} 我想这不是必须要做的,不是吗?此外,这不是一个枯燥的代码:-( import React,{Component}来自“React” 从“同构取消蚀刻”导入提取 类索引扩展组件{ 静态异步getInitialProps(){ const api=process.env.NODE_env==='production' ? 'http:

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

我想这不是必须要做的,不是吗?此外,这不是一个枯燥的代码:-(

import React,{Component}来自“React”
从“同构取消蚀刻”导入提取
类索引扩展组件{
静态异步getInitialProps(){
const api=process.env.NODE_env==='production'
? 'http://172.17.0.2:3000/get-数据的
: 'http://localhost:3000/get-数据的
const res=等待获取(api)
return res.json()
}
建造师(道具){
超级(道具)
常数{温度,湿度}=props
此.state={
温度
湿度
}
}
组件安装(){
this.interval=setInterval(
异步()=>{
const api=process.env.NODE_env==='production'
? 'http://172.17.0.2:3000/get-数据的
: 'http://localhost:3000/get-数据的
const res=等待获取(api)
const data=await res.json()
此.setState(数据)
}, 3000)
}
组件将卸载(){
clearInterval(this.interval)
}
渲染(){
常数{湿度,温度}=此状态
返回(
{湿度}%
{温度}摄氏度
)
}
}
导出默认索引

这应该可以,不需要
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();
}

我想说的是,将api逻辑放入不同的文件中。而不是在3秒钟后调用api。最好是从服务器推送数据。比如使用web套接字。
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();
}