Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/443.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Usestate未更新_Javascript_React Native - Fatal编程技术网

Javascript Usestate未更新

Javascript Usestate未更新,javascript,react-native,Javascript,React Native,我尝试在动画结束时更新状态的值,但当我尝试这样做时,它不会更新。如果我使用一个按钮来更新这个值,那么它就工作了。检查我做的这个函数 const [imgIndex, setImgIndex] = useState(0) function startAnim() { Animated.timing(animationValue, { duration: 2000, toValue: windowWidth, easing: Easing.li

我尝试在动画结束时更新状态的值,但当我尝试这样做时,它不会更新。如果我使用一个按钮来更新这个值,那么它就工作了。检查我做的这个函数

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。
如果有人知道它的解决方案,请帮助我。

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

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

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


你能分享整个组件吗?谢谢Tauseef的回答和简短的解释imgindexref.current=count;这算什么?对不起,我的错,把计数改成了imgIndex。
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()
        }
      });
    }