P粉0345716232023-08-15 15:59:32
Side effects in loops: The way you use setTimeout and setIndex in useEffect may cause unexpected behavior. useEffect is executed after each render, and using the index state directly in the setTimeout callback may cause problems because the closure captures the state value when the callback is created.
Accessing array elements: You are trying to access an element of the users array using an index, but due to the asynchronous nature of useEffect and delay, it is possible to exceed the scope of the array.
const [index, setIndex] = useState(0); useEffect(() => { console.log('RENDER'); console.log('副作用运行!'); if (index >= users.length) { return; } const timeoutId = setTimeout(() => { console.log('你好 ' + users[index]); setIndex(index + 1); }, 1000); return () => clearTimeout (timeoutId); }, [index]);