【问题标题】:React native how to make counterReact Native 如何制作计数器
【发布时间】:2020-09-05 21:03:45
【问题描述】:

嗨,这只是一个非常简单的问题,但我不知道为什么它不起作用。 所以我的代码是

  const [i, seti] = useState(0);

我只想将状态更新为 1 inc onPress Touchableopacity。它在第一次点击时不起作用,然后在第二次点击时它开始工作。

     <TouchableOpacity style={listStyles.buttonstyle2} onPress={() =>
      {     
        console.log('Before  i '+i);
              //trying to update
        seti(current => current + 1);
        console.log('After  i '+i);

        if(i%2==1) {setisPress(false); )  }
        else  {setisPress(true) }
      }
    }>   

【问题讨论】:

  • 是的,看起来像 dup,但我看到了这些问题,但我无法申请自己
  • 所以如果你知道i 不会立即改变它的值,你就无法弄清楚如何改变代码以便它使用i+1 来代替?
  • 没错。我认为这是一个简单的问题
  • 好的,这里有个提示:用if(i%2==0)替换if(i%2==1)

标签: react-native


【解决方案1】:

使用应该使用 useEffect(()=>{...} , [i])

useEffect(()=>{
    console.log('After  i '+i);
    if(i%2==1) {setisPress(false); )  }
    else  {setisPress(true) }
}, [i]) 

return(
  <TouchableOpacity style={listStyles.buttonstyle2} onPress={() =>
      {     
        console.log('Before  i '+i);
              //trying to update
        seti(current => current + 1);
        
      }
    }>  

)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    • 1970-01-01
    • 2021-11-22
    相关资源
    最近更新 更多