Usestate未更新

时间:2020-07-14 11:32:41

标签: javascript react-native

我试图在动画结束时更新状态的值,但是当我尝试这样做时,它并没有更新。如果我使用按钮来更新该值,那么它将起作用。检查我做的这个功能

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()
        }
    });
}

在每个动画的末尾,我正在使用setImgIndex(imgIndex + 1),该值应该被更新但不更新,每次在控制台上打印为0时,该动画就可以正常工作 我也使用setInterval尝试了相同的方法,但是在setInterval中,它每次都会打印0。 如果有人知道其解决方案,请帮助我。

2 个答案:

答案 0 :(得分:2)

由于您在动画定时回调中使用状态值,因此它引用的是旧值。

  • 因此,对于回调,您必须使用ref作为正确的参考
  • 要在回调中设置状态,请像setImgIndex(imgIndex => imgIndex + 1)

供参考: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()
        }
      });
    }

答案 1 :(得分:-1)

也许,您应该使用setTimeout进行打印。因为imgIndex不会立即更新,所以您可能看不到更新的索引。

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)
        }
    });
}