简体   繁体   中英

usestate hooks combined with timers not working properly inside useeffect hook

Here I used usestate hook for val

my code is updating val correctly through an extra global variable g when setinterval is calling tick function!!

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?? 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.

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. 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.

setvalue( prevValue => prevValue + 0.01 )

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