Equivalent to componentDidUpdate using React hooks

前端 未结 4 1370
暗喜
暗喜 2020-12-13 06:10

tldr; How do I simulate componentDidUpdate or otherwise use the key prop with an array to force my component to be reset?

4条回答
  •  感动是毒
    2020-12-13 06:54

    In short, you want to reset your timer when the reference of the array changes, right ? If so, you will need to use some diffing mechanism, a pure hooks based solution would take advantage of the second parameter of useEffect, like so:

    function RefresherTimer(props) {
      const [startedAt, setStartedAt] = useState(new Date());
      const [timeRemaining, setTimeRemaining] = useState(getTimeRemaining(startedAt, props.delay));
    
      //reset part, lets just set startedAt to now
      useEffect(() => setStartedAt(new Date()),
        //important part
        [props.listOfObjects] // <= means: run this effect only if any variable
        // in that array is different from the last run
      )
    
      useEffect(() => {
        // everything with intervals, and the render
      })
    }
    

    More information about this behaviour here https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects

提交回复
热议问题