我想重复这个动作并每10秒重新渲染一次。有人能帮我一下吗?
useEffect(() => {
const fetchData = async () => {
setIsLoading(true)
const response = await coinGecko.get("/coins/markets", {
params: {
vs_currency: "usd",
ids: watchList.join(","),
}
})
setCoins(response.data)
setIsLoading(false)
}
fetchData()
},[])
定义状态:const [repeater,setRepeater]=useState(0)
在你的useEffect中把它作为第二个参数传递,所以当它被改变时,你的useEffect会再次运行。现在让我们用这段代码来处理10秒的间隔:setTimeout(() => setRepeater(prevState=>prevState+1), 100000);
最后像这样实现它:
useEffect(() => {
const fetchData = async () => {
setIsLoading(true)
const response = await coinGecko.get("/coins/markets", {
params: {
vs_currency: "usd",
ids: watchList.join(","),
}
})
setCoins(response.data)
setIsLoading(false)
}
fetchData()
setTimeout(() => setRepeater(prevState=>prevState+1), 100000);
},[repeater])