react-native - 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) }
}
}>
解决方案
使用应该使用 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);
}
}>
)
推荐阅读
- node.js - 如何在nodejs中访问对象键,其中键为'category.0'格式
- postgresql - 通过几个条件将某个表连接到 generate_series 日期表
- bots - 我想制作一个机器人来简化我在 soundcloud 上的音乐流媒体体验
- java - 将消息写入代理后,Spark kafka 连接器抛出空指针异常
- powershell - 如何使用 Powershell 删除或替换字符串开头的模式?
- unit-testing - 用 jest 测试 type-graphql 中间件的正确方法
- xamarin.forms - 如何初始化`LocalizationResourceManager`
- python - 解析函数名称,参数,从python文件返回值?
- sql - 如何使用存储过程在commo之后拆分任何列字符串记录
- reactjs - 选择 mdbreact 表中的任何行时更新行背景(Reactjs)