我在使用useState的react native中有一个计数器递增器。每当我按下按钮时,计数都应该增加一。然而,当第一次按下时计数器仍然为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',
},
});