简体   繁体   中英

Usestate is not updating

I am trying to update the value of a state at the end of an animation, but when I am trying to do so, it's not updating. If I use a button to update that value then it's working. Check this function which I made

const [imgIndex, setImgIndex] = useState(0)
function startAnim() {
    Animated.timing(animationValue, {
        duration: 2000,
        toValue: windowWidth,
        easing: Easing.linear,
        useNativeDriver: true,
    }).start(({ finished }) => {
        if (imgIndex != images.length - 1) {
            setImgIndex(imgIndex + 1)
            console.log(imgIndex)
            animationValue.setValue(0)
            startAnim()
        }
    });
}

at the end of every animation, I am using setImgIndex(imgIndex + 1) which should get updated but it's not updating, in console every time it's print 0. but the animation is working fine I also try this same method with setInterval, but again in setInterval, it prints 0 every time. If anyone knows its solution then please help me.

Since you are using state value in an animation timed callback it refers to the old value.

  • So for callback you have to use ref for the correct reference
  • To set state in callback do it like setImgIndex(imgIndex => imgIndex + 1)

For Reference: https://github.com/facebook/react/issues/14010#issuecomment-433788147

const [imgIndex, setImgIndex] = useState(0)
    const imgIndexRef = useRef(imgIndex);
    imgIndexRef.current = imgIndex;
    function startAnim() {
      Animated.timing(animationValue, {
        duration: 2000,
        toValue: windowWidth,
        easing: Easing.linear,
        useNativeDriver: true,
      }).start(({ finished }) => {
        if (imgIndexRef.current != images.length - 1) {
          setImgIndex(imgIndex => imgIndex + 1)
          console.log(imgIndexRef.current)
          animationValue.setValue(0)
          startAnim()
        }
      });
    }

Maybe, you should use setTimeout for printing. Because imgIndex is not updated immediately, so you may not see your updated index.

const [imgIndex, setImgIndex] = useState(0)
function startAnim() {
    Animated.timing(animationValue, {
        duration: 2000,
        toValue: windowWidth,
        easing: Easing.linear,
        useNativeDriver: true,
    }).start(({ finished }) => {
        if (imgIndex != images.length - 1) {
            setImgIndex(imgIndex + 1)
            setTimeout(() => {
                console.log(imgIndex)
                animationValue.setValue(0)
                startAnim()
            }, 150)
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM