简体   繁体   中英

Basic Beginner React-Native State Question

Hello guys I just started learning React-Native and I have a question about state.

I was practicing this concept trying to make a button that shows how many times I've pressed it.

My plan was to make a variable called clicks which will increase by 1 each time I press it and set the clickState to clicks. This is my code.

    export default function App() {
  const [clickState, setClicks] = useState(0)
  let clicks = 0
  return (
    <View style = {styles.container}>
      <StatusBar style="auto" />
      <TouchableOpacity style={styles.button} onPress={()=>{setClicks(++clicks); console.log(clicks)}}>
        <Text>Clicks : {clickState}</Text> 
      </TouchableOpacity>
    </View>
  );
}

this is the console

But apparently something is wrong and my clicks value goes random between 1 and 2 each time I click it instead of increasing by 1.

So I was curious about what I was doing wrong and why the values don't increase as I expected. I would also be glad if you showed how you would implement it if there is a better way.

Thanks guys.

You only need to update clickState , no need of variable clicks . Also it won't rerender if we increment state value directly, so we should increment state by taking its previous state value like shown below

export default function App() {
  const [clickState, setClicks] = useState(0)
  return (
    <View style = {styles.container}>
      <StatusBar style="auto" />
      <TouchableOpacity style={styles.button} onPress={()=>setClicks(prevState => prevState + 1)}>
        <Text>Clicks : {clickState}</Text> 
      </TouchableOpacity>
    </View>
  );
}

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