简体   繁体   English

usestate 挂钩与计时器在 useeffect 挂钩内无法正常工作

[英]usestate hooks combined with timers not working properly inside useeffect hook

Here I used usestate hook for val这里我使用了 usestate 钩子作为val

my code is updating val correctly through an extra global variable g when setinterval is calling tick function!!setinterval调用tick函数时,我的代码正在通过一个额外的全局变量g正确更新val

import React, { useEffect, useState } from 'react';
import { TextInput } from 'react-native';
import { Button } from 'react-native';
import { ImageBackground } from 'react-native';
import { StyleSheet, View, FlatList, Alert, TouchableWithoutFeedback,TouchableOpacity, Keyboard,Text} from 'react-native';
import Icon from 'react-native-vector-icons/AntDesign';
import Slider from '@react-native-community/slider';
import * as Progress from 'react-native-progress';
export default function Status({route,navigation}) {
  let [val,setvalue]=useState(0);
  var g=0;
  useEffect(()=>{
    setTimeout(() => {
      navigation.navigate('Home',{xx:"hhh"});
    }, 5000);
   
  },[]);
  useEffect(() => {
    const x=setInterval(tick, 50);
     return ()=>{
            clearInterval(x);
     }
  },[])
  function tick()
  {
    console.log('hi');
    g=g+0.01;
    setvalue(g);
  }
  const {image,text}=route.params;
  return(
    <View style={styles.container}>
        <ImageBackground source={{uri:image}} imageStyle={styles.image} style={styles.border}>
          <Progress.Bar  progress={val} width={null} />
          <Text  style={styles.input}>{text}</Text>
        </ImageBackground>
    </View>
  );
}
const styles = StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: 'red'
    },
    image: {
        flex:1,
        resizeMode: 'cover'
      },
      border: {
        flex:1,
        justifyContent:'flex-end'
      },
      input: {
        flex:1,
        height: 40,
        fontSize:20,
        padding:2,
        color:'white',
        //width:null,
        marginTop: 500,
        marginBottom:10,
        borderWidth: 0,
        borderColor:null,
        borderRadius:10,
        alignSelf:'center'
      }
});

but here my code is not updating val when setinterval is calling tick function??但是当setinterval调用Tick function 时,我的代码没有更新val please help!!请帮忙!!

import React, { useEffect, useState } from 'react';
import { TextInput } from 'react-native';
import { Button } from 'react-native';
import { ImageBackground } from 'react-native';
import { StyleSheet, View, FlatList, Alert, TouchableWithoutFeedback,TouchableOpacity, Keyboard,Text} from 'react-native';
import Icon from 'react-native-vector-icons/AntDesign';
import Slider from '@react-native-community/slider';
import * as Progress from 'react-native-progress';
export default function Status({route,navigation}) {
  let [val,setvalue]=useState(0);
  
  useEffect(()=>{
    setTimeout(() => {
      navigation.navigate('Home',{xx:"hhh"});
    }, 5500);
   
  },[]);
  useEffect(() => {
    const x=setInterval(tick, 50);
     return ()=>{
            clearInterval(x);
     }
  },[])
  function tick()
  {
    console.log('hi');
    setvalue(val+0.01);
  }
  const {image,text}=route.params;
  return(
    <View style={styles.container}>
        <ImageBackground source={{uri:image}} imageStyle={styles.image} style={styles.border}>
          <Progress.Bar  progress={val} width={null} />
          <Text  style={styles.input}>{text}</Text>
        </ImageBackground>
    </View>
  );
}
const styles = StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: 'red'
    },
    image: {
        flex:1,
        resizeMode: 'cover'
      },
      border: {
        flex:1,
        justifyContent:'flex-end'
      },
      input: {
        flex:1,
        height: 40,
        fontSize:20,
        padding:2,
        color:'white',
        //width:null,
        marginTop: 500,
        marginBottom:10,
        borderWidth: 0,
        borderColor:null,
        borderRadius:10,
        alignSelf:'center'
      }
});

Here I am using a progress bar and It should update progress automatically for 5 seconds and after I am navigating to another home screen.在这里,我使用了一个进度条,它应该在 5 秒内自动更新进度,并且在我导航到另一个主屏幕之后。

I want to know why my second code is not working as expected as from the first code??我想知道为什么我的第二个代码不像第一个代码那样工作?

setvalue is asynchronous function and because of this value is not set immediately after call. setvalue是异步的 function 并且由于该值在调用后不会立即设置。 You try to update value based on current value in short range of time which cause the issue.您尝试在导致问题的短时间内根据当前值更新值。 You should use callback passed to setvalue which get you correct previous value event if state will not have time to update yet.如果 state 还没有时间更新,您应该使用传递给setvalue的回调来纠正先前的值事件。

setvalue( prevValue => prevValue + 0.01 )

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

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