简体   繁体   中英

React Native : make useState update on real time

I have this code on react native where I increment a counter by 1 after each button press

     function App() {
          const [counter,setCounter]=useState(0);
          return (
            <View>
              <Button title="hello" onPress={()=> 
              {setCounter(counter+1);console.log("display 
               counter in console" ,counter)}}>
                </Button>

              {counter%2==1 ? <Text> display counter in UI</Text> 
               : null }
    
               <View>
               <Text> thank you for clicking the button </Text>
               </View>
        
            </View>
           )
             }

After the first click the counter is equal to 0 and the console shows 0 instead of 1 so the JSX component won't show. I know that useState is asynchronous but how to solve it if showing a JSX is depending on updating the state on real time.

UPDATE: It seems that the JSX displays when excpected but I'm wondering why console.log will not update on real time ? I mean why console.log shows 0 when it is supposed to show 1

You just need to add pre-increment operator on setCounter state. and Change const to var in useState declaration.

https://snack.expo.dev/j70TThHHb

export default function App() {
              var [counter,setCounter]=useState(0);
              return (
                <View style={{marginTop:25}}>
                  <Button title="hello" onPress={()=> 
                  {setCounter(++counter);
                  console.log("display  counter in console" ,counter)}}>
                    </Button>
    
                  {counter%2==1 ? <Text> display counter in UI</Text> 
                   : null }
        
                   <View>
                   <Text> thank you for clicking the button </Text>
                   </View>
            
                </View>
               )
                 }

useState hook is asynchronous, so you can not access it's new values immediately
And there is no callback for it (unlike setState )
But if you want to listen to it's changes, you can use useEffect hook like this

useEffect(() => {
    console.log('display  counter in console', counter);
}, [counter]);

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