繁体   English   中英

使用状态未更新

[英]Usestate is not updating

我正在尝试在 animation 的末尾更新 state 的值,但是当我尝试这样做时,它并没有更新。 如果我使用按钮来更新该值,那么它就可以工作。 检查我制作的这个 function

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

在每个 animation 结束时,我使用 setImgIndex(imgIndex + 1) 应该更新但它没有更新,每次打印 0 时在控制台中。但 animation 工作正常我也尝试使用 setInterval 使用相同的方法,但又一次在 setInterval 中,它每次都打印 0。 如果有人知道它的解决方案,请帮助我。

由于您在 animation 定时回调中使用 state 值,因此它指的是旧值。

  • 因此,对于回调,您必须使用 ref 作为正确的参考
  • 在回调中设置 state 像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()
        }
      });
    }

也许,您应该使用 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)
        }
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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