在useEffect挂钩中的计时器期间,我无法及时更新数组:
const [data, setData] = useState(0)
const [priceList, setPriceList] = useState([])
const [profit, setProfit] = useState(0)
useEffect(() => {
let value = 1000
const update_value = () => {
if (Math.random() >= 0.5 || value - Math.floor(Math.random() * 500) + 100 < 0) {
return value += Math.floor(Math.random() * 500) + 100
}
return value -= Math.floor(Math.random() * 500) + 100
}
const price_fluctuation = (d) => {
if (priceList.length < 2) {
setPriceList([d, ...priceList])
return d
} else {
let oldList = [...priceList]
oldList.pop()
setPriceList([d, ...oldList])
return d - priceList[1]
}
}
const timer = () => {
let totalTimer = (5 * 60 + 1) * 1000
let timerId = setInterval(
() => {
const current_price = update_value()
setData(current_price)
setProfit(price_fluctuation(current_price))
}, 5000);
setTimeout(() => { clearInterval(timerId); }, totalTimer);
}
timer()
}, [])
函数price_fluctuation获取当前价格并将其添加到一个数组中,然后将其设置为priceList。该功能旨在最多保留当前价格和先前价格两个价格。但是,priceList不会在计时器期间设置,我相信这是因为priceList始终被初始化为空数组。
在计时器期间如何使我的功能按预期工作。我相信我误会了。