Storing non-state variables in functional components

后端 未结 4 1127
梦谈多话
梦谈多话 2020-12-25 10:45

Below are two React Components that do almost the same thing. One is a function; the other is a class. Each Component has an Animated.Value with an asy

4条回答
  •  爱一瞬间的悲伤
    2020-12-25 11:38

    This is a pretty unusual example, but if I'm reading this correctly, you simply want to store unique _foo objects everytime the component mounts and destroy them when it unmounts, but also prevent extra rerenders when this value changes.

    I have run into this scenario before and simple object (map / hash) should do the trick:

    let foos = {}
    let fooCount = 0
    
    function F(props) {
      useEffect(() => {
        let fooId = fooCount++
        foos[fooId] = new Animated.Value(0)
        foos[fooId].addListener(...)
        return () => foos[fooId].removeListener(...)
      }, []) // <-- do not rerun when called again (only when unmounted)
    
      ...render...
    }
    

    or something to that effect. if you have a runnable example could tweak it to make it fit your example better. either way, most things with scope problems are solved with primitives.

提交回复
热议问题