简体   繁体   English

基础初学者 React-Native State 问题

[英]Basic Beginner React-Native State Question

Hello guys I just started learning React-Native and I have a question about state.大家好,我刚开始学习 React-Native,我有一个关于 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.我的计划是创建一个名为 clicks 的变量,每次按下它并将 clickState 设置为 clicks 时,该变量将增加 1。 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.但显然出了点问题,每次点击它时我的点击值在 1 到 2 之间随机变化,而不是增加 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 .您只需要更新clickState ,不需要变量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此外,如果我们直接增加 state 值,它也不会重新渲染,所以我们应该通过取之前的 state 值来增加 state 值,如下所示

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>
  );
}

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

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