假设我有以下状态
const [states, setStates] = useState([
{name: '', age: '', amount: ''},
{name: '', age: '', amount: ''},
]);
const total = 0;
I wish to use useEffect
to update only when age
fields are changed to calculate the amount
fields. And then update the total
field based on the amount
fields changed. How do I do that? In this example, I have small number of array with three fields, but in reality, I have a big array with a lot of fields, so I don't want to use useEffect
when any fields in states
change.
The short answer is that you can't do that - the
useEffect
hook doesn't provide the ability to keep track of specific object properties inside of an array.You'd have to keep track of another piece of state that will change if any of the
age
properties change, which will trigger theuseEffect
that has that piece of state in the dependency array.