如何在 React 组件中每分钟调用一个函数?

编程入门 行业动态 更新时间:2024-10-26 20:25:00
本文介绍了如何在 React 组件中每分钟调用一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我制作了一个表格来获取股票报价,效果很好,但是当我尝试在组件中放置一个包含 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 组件中每分钟调用一个函数?

本文发布于:2023-06-07 15:28:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/568625.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:每分钟   组件   一个函数   如何在   React

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!