我没有得到任何错误,但当我运行React Native应用程序result
将保持false
。当我点击Generate Number
-undefined
将打印到控制台,但TextInput
下将出现一个随机数,当我再次点击时,将出现一个新的数字,但旧的数字将打印到控制台。这是我的代码:
import React, { useState } from 'react';
import { View, Text, TextInput, Button, StyleSheet } from 'react-native';
const App = () => {
const [number, setNumber] = useState();
const [result, setResult] = useState(false);
const styles = StyleSheet.create({
...
});
const guess = (num) => {
if (num === number) {
setResult(true);
} else {
setResult(false);
}
console.log(result);
};
const genNumber = () => {
setNumber(Math.floor(Math.random() * (100 - 1) + 1));
console.log(number);
};
return (
<View style={styles.view}>
<Button onPress={() => genNumber()} title="Generate Number" />
<TextInput
style={styles.text}
onChangeText={(text) => guess(text)}
placeholder="Enter your guess"
/>
<Text style={styles.text}>{number}</Text>
</View>
);
};
export default App;
可能是作用域错误,但我不确定。
useState
是异步的,正如评论中提到的,所以您可以使用useEffect
订阅状态更改,或者您可以这样做:
const genNumber = async () => {
await setNumber(Math.floor(Math.random() * (100 - 1) + 1));
console.log(number);
};