Why does useEffect ignore the last element of the array?
P粉814160988
P粉814160988 2023-08-14 18:21:42
0
1
338

I am learning React, especially learning useEffect.

What I can't figure out is why useEffect skips the last element of the array.

Can someone kindly explain why and how to fix it?

let users = ['Oliver', 'Thomas', 'George', 'William'] export default function App() { const [index, setIndex] = useState(0); console.log('RENDER'); useEffect(() => { if (index === users.length - 1) { return } setTimeout(() => setIndex(index => index 1), 2000) console.log('Hello ' users[index]); console.log('Side Effect RUNS!'); }, [users[index]]) }


P粉814160988
P粉814160988

reply all (1)
P粉553428780

YouruseEffectwill not run becauseusers[index]has the same value

Change it toindex

let users = ['Oliver', 'Thomas', 'George', 'William'] export default function App() { const [index, setIndex] = useState(0); console.log('RENDER'); useEffect(() => { if (index === users.length - 1) { return } setTimeout(() => setIndex(index => index + 1), 2000) console.log('Hello ' + users[index]); console.log('Side Effect RUNS!'); }, [index]) // 更改为 `[index]` }
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!