reactjs - 在本机反应中抵消一
问题描述
我在 react-native 中有一个使用 useState 的计数器增量器。每当我按下一个按钮时,计数应该加一。它工作正常,但是当第一次按下时,计数器仍然为 0,当第二次按下时,计数器增加 1 并顺利继续,没有问题。为什么第一版不更新?这是代码:
import { StatusBar } from 'expo-status-bar';
import React, {useState } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
export default function App() {
const [count, setCount] = useState(0);
const [outputState, setOutputState] = useState(`You have tapped ${count} times`);
const getFinalResult = () => {
setCount(count => count + 1);
setOutputState(`You have tapped ${count} times`);
}
return (
<View style={styles.container}>
<Text>{outputState}</Text>
<Button title="change text" onPress={getFinalResult} />
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
解决方案
此代码将为您工作。您正在同时设置状态和显示。设置状态是异步任务,需要一些时间才能完成。
import { StatusBar } from 'expo-status-bar';
import React, {useState } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
export default function App() {
const [count, setCount] = useState(0);
return (
<View style={styles.container}>
<Text>You have tapped {count} times</Text>
<Button title="change text" onPress={() => setCount(count => count + 1)} />
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
推荐阅读
- postgresql - Yii2:如何为我的模型添加检查约束?
- cakephp - 将 VueJS 与 CakePHP 3 集成的最佳实践
- php - 使用 PHP 提取 JSON 数据
- ruby - 替代转义的外壳字符串?
- ios - unity ios 使用 https 无法进行休息标注
- python - Pandas 将行分配给匹配行的索引
- c# - 如果您知道居中坐标,请在图片上创建相等的框
- php - 无法将表单中的数据插入 MySQL;用 PHP
- ruby-on-rails - 使用haml将coffeescript放置在rails视图上的ruby末尾时收到语法错误
- s4sdk - Cloud-SDK 按子字段过滤