仅当状态中的某些字段已更改时,useEffect才会更新

假设我有以下状态

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.

评论
  • punde
    punde 回复

    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 the useEffect that has that piece of state in the dependency array.

    const [states, setStates] = React.useState([...])
    const [lastAgeUpdatedAt, setLastAgeUpdatedAt] = React.useState(null)
    // const total = 0; // by the way, this looks like something that 
                        // should also be stored in a state,
                        // the below would be more appropriate
    const [total, setTotal] = React.useState(0)
    
    const handleUpdateAge = () => {
      setStates(...)
      if (ageUpdatesAvailable) {
        setLastAgeUpdatedAt(Date.now())
      }
    }
    
    
    React.useEffect(() => {
      const total = states.reduce(
        (accumulator, result) => accumulator + result.age, 
        0
      )
    }, [lastAgeUpdatedAt])