如何在 React 组件中每分钟调用一个函数? [英] How to call a function every minute in a React component?
问题描述
我制作了一个表格来获取股票报价,效果很好,但是当我尝试在组件中放置一个包含 setState 的函数时,它陷入了无限循环,它会立即触发 setState 并重新渲染并再次触发.
I make a table to get stock price quotes, it works well, but when I try to put a function include setState in the component, it falls into an infinite loop, it triggers setState and re-render immediately and triggers again.
如何在加载此组件时调用此函数而不触发无限循环?我会每 10 秒或每分钟调用一次该函数.
How can I call this function without triggering an infinite loop when I load this component? I would to call the function every 10 seconds or every minute.
import React, { useState } from 'react'
import api from '../../api'
function CreateRow(props){
const [stock, setStock] = useState({symbol:'',last:'',change:''})
async function check() {
const result = await api.getStock(props.item)
console.log(props.item)
const symbol = result.data.symbol
const lastest = result.data.latestPrice
const change = result.data.change
setStock({symbol:symbol, lastest:lastest, change:change})
}
// check() <----------! if I call the function here, it becomes an infinite loop.
return(
<tr>
<th scope="row"></th>
<td>{stock.symbol}</td>
<td>{stock.lastest}</td>
<td>{stock.change}</td>
</tr>
)
}
export default CreateRow
推荐答案
您想在生命周期方法中启动超时函数.
You want to initiate a timeout function inside a lifecycle method.
生命周期方法是调用方法,例如挂载和卸载(示例更多,但为了解释起见,我将在这里停止)
Lifecycle methods are methods which call on, for example, mount and unmount (there are more examples but for the sake of explanation I will stop here)
您感兴趣的是挂载生命周期.
what you're interested in is the mount lifecycle.
在功能组件中,可以这样访问:
In functional components, it can be accessed like this:
const { useEffect } from 'react';
useEffect(() => {
// This will fire only on mount.
}, [])
在那个函数中,你想初始化一个 setTimeout
函数.
In that function, you want to initialize a setTimeout
function.
const MINUTE_MS = 60000;
useEffect(() => {
const interval = setInterval(() => {
console.log('Logs every minute');
}, MINUTE_MS);
return () => clearInterval(interval); // This represents the unmount function, in which you need to clear your interval to prevent memory leaks.
}, [])
这篇关于如何在 React 组件中每分钟调用一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!