我正在制作一个表格来获取股票价格报价,它运行良好,但是当我尝试在组件中放置包含
setState
的函数时,它陷入无限循环,它会触发 setState
并立即重新渲染并再次触发。
如何在加载该组件时调用该函数而不触发无限循环? 我想每 10 秒或每分钟调用一次该函数。
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
您想在生命周期方法内启动超时函数。
生命周期方法是调用诸如挂载和卸载之类的方法(还有更多示例,但为了解释起见,我将在此停止)
您感兴趣的是挂载生命周期。
在功能组件中,可以这样访问:
import { useEffect } from 'react';
useEffect(() => {
// This will fire only on mount.
}, [])
在该函数中,您想要初始化一个
setTimeout
函数。
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.
}, [])
考虑 60000 毫秒 = 1 分钟
可以使用以下方法:
setInterval(FunctionName, 60000)
执行以下操作:
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})
}
// Write this line
useEffect(() => {
check()
}, []);
setInterval(check, 60000);
import React, { useState, useEffect } from "react";
export const Count = () => {
const [currentCount, setCount] = useState(1);
useEffect(() => {
if (currentCount <= 0) {
return;
}
const id = setInterval(timer, 1000);
return () => clearInterval(id);
}, [currentCount]);
const timer = () => setCount(currentCount + 1);
console.log(currentCount);
return <div>Count : - {currentCount}</div>;
};
你也可以使用 setTimeout 来做到这一点
import React, { useState, useEffect } from "react";
export const Count = () => {
const [counts, setcounts] = useState(0);
async function check() {
setcounts(counts + 1);
}
// Write this line
useEffect(() => {
check();
}, []);
console.log("hello dk - ",counts)
setTimeout(() => {
check();
}, 1000);
return <div>Count : - {counts}</div>;
};