[英]Fetch data from external Api with reactjs hooks in every 10 seconds
I use React js hooks to fetch data from api every 10 seconds in UseEffect.我使用 React js 挂钩在 UseEffect 中每 10 秒从 api 获取数据。 The problem is that it takes 10 seconds to do the state update first.
问题是首先进行 state 更新需要 10 秒。 So before the setInterval function, I need to fetch the data once the component is not rendered.
所以在 setInterval function 之前,一旦组件没有渲染,我需要获取数据。
Code part is here:代码部分在这里:
function getList() {
return axios.post('http://localhost:5000/getParameters', { no: no, name: name })
.then(data => data.data)
}
function getParams() {
return axios.post('http://localhost:5000/getParametersSite', { no: no, name: name })
.then(data => data.data)
}
useEffect(() => {
let mounted = true;
let isMounted = true
const intervalId = setInterval(() => {
getParams()
.then(itemsa => {
if(mounted) {
setParams(itemsa)
}
})
getList()
.then(items => {
if(mounted) {
setMenuData(items)
}
})
}, 10000)
return () => {
clearInterval(intervalId);
isMounted = false
mounted = false;
}
}, [menuData,params])
You can use a useRef
hook to know if it is the first render.您可以使用
useRef
挂钩来了解它是否是第一次渲染。 like this:像这样:
const firstUpdate = useRef(true);
useEffect(() => {
let mounted = true;
let isMounted = true
if (firstUpdate.current) {
firstUpdate.current = false;
getParams()
.then(itemsa => {
if(mounted) {
setParams(itemsa)
}
})
getList()
.then(items => {
if(mounted) {
setMenuData(items)
}
})
}
const intervalId = setInterval(() => {
getParams()
.then(itemsa => {
if(mounted) {
console.log("getParams",itemsa);
setParams(itemsa)
}
})
getList()
.then(items => {
if(mounted) {
console.log("setParams",items);
setMenuData(items)
}
})
}, 10000)
return () => {
clearInterval(intervalId);
mounted = false;
}
}, [menuData,params])
like explain in react doc :就像在反应文档中解释:
useRef returns a mutable ref object whose.current property is initialized to the passed argument (initialValue).
useRef 返回一个可变的 ref object,其.current 属性初始化为传递的参数 (initialValue)。 The returned object will persist for the full lifetime of the component.
返回的 object 将在组件的整个生命周期内持续存在。
So no matter if your component render again.因此,无论您的组件是否再次渲染。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.