In React, if you want to trigger an effect only when the array length changes, you can include the array's length in the dependency array of useEffect. This ensures that the effect is re-executed only when the array length changes.
Here is an example implementation:
jsximport React, { useState, useEffect } from 'react'; function MyComponent() { const [items, setItems] = useState([]); useEffect(() => { // This effect triggers when the items array length changes console.log('Array length has changed:', items.length); }, [items.length]); // Depends on array length // A function to add a new item to the array const addItem = () => { setItems(prevItems => [...prevItems, `Item ${prevItems.length}`]); }; return ( <div> <button onClick={addItem}>Add Item</button> <ul> {items.map((item, index) => ( <li key={index}>{item}</li> ))} </ul> </div> ); }
In the above example, we create a MyComponent component that includes a items state array and an addItem function to add new items to the array. useEffect depends on items.length, so it only outputs the new value of the array length when the array length changes.
2024年6月29日 12:07 回复