gpt4 book ai didi

reactjs - 使用 useState 和 setInterval react useEffect

转载 作者:行者123 更新时间:2023-12-03 18:18:58 25 4
gpt4 key购买 nike

使用以下代码通过组件 DOM 旋转对象数组。问题是状态永远不会更新,我不能锻炼为什么..?

    import React, { useState, useEffect } from 'react'

const PremiumUpgrade = (props) => {
const [benefitsActive, setBenefitsActive] = useState(0)


// Benefits Details
const benefits = [
{
title: 'Did they read your message?',
content: 'Get more Control. Find out which users have read your messages!',
color: '#ECBC0D'
},
{
title: 'See who’s checking you out',
content: 'Find your admirers. See who is viewing your profile and when they are viewing you',
color: '#47AF4A'
}
]


// Rotate Benefit Details
useEffect(() => {
setInterval(() => {
console.log(benefits.length)
console.log(benefitsActive)

if (benefitsActive >= benefits.length) {
console.log('................................. reset')
setBenefitsActive(0)
} else {
console.log('................................. increment')
setBenefitsActive(benefitsActive + 1)
}
}, 3000)
}, [])

我得到的输出如下图所示。我可以看到 useState 'setBenefitsActive' 正在被调用,但 'benefitsActive' 从未更新。

enter image description here

最佳答案

您没有将依赖项传递给 useEffect意味着它只会运行一次,因此 setInterval 的参数只会收到初始值 benefitsActive (在这种情况下是 0 )。

您可以使用函数修改现有状态,而不仅仅是设置值,即

setBenefitsActive(v => v + 1);

关于reactjs - 使用 useState 和 setInterval react useEffect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58133327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com