首页 > 解决方案 > React Native 如何制作计数器

问题描述

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

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

标签: react-native

解决方案


使用应该使用 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);
        
      }
    }>  

)


推荐阅读