我刚刚开始学习一些本机反应,我正在尝试制作一个简单的 cookie 点击器应用程序。当我点击我的 cookie 时,cookiecount 会增加 1,但我希望 cookie 计数每秒也增加 1。当我多次点击 cookie 并且 cookiecount 翻转并跳转到不同的数字并再次返回时,我认为这与我同时更新 cookiecount 状态 2 次有关?
export default function App(props) {
{/* Make the state that holds the amount of cookies */}
const [cookieCount, modifyCookieCount] = useState(0)
const [costCount, modifyCostCount] = useState(10)
const [perClickBoost, setBoost] = useState(1)
const interval = setInterval(() => modifyCookieCount(cookieCount+1), 1000);
function addPurchase(count){
modifyCookieCount(cookieCount-count)
modifyCostCount(costCount+10);
setBoost(perClickBoost+1)
}
return (
<View style={styles.container}>
<Text>{cookieCount}</Text>
{/* TouchableOpacity is needed to make use of Onpress prop */}
<TouchableOpacity onPress = {addCookie}>
<Image style={styles.image} source={require('./images/cookie.png')}/>
</TouchableOpacity>
<Purchasables addPurchase={addPurchase} count={cookieCount} title='Koekjesslaaf' cost={costCount}/>
<StatusBar style="auto" />
</View>
);
function addCookie(){
{/* Add a cookie */}
modifyCookieCount(cookieCount+perClickBoost)
}
}
该问题是由这两个更新引起的:
const interval = setInterval(() => modifyCookieCount(cookieCount+1), 1000);
和
function addCookie(){
{/* Add a cookie */}
modifyCookieCount(cookieCount+perClickBoost)
}
我希望有人可以帮助我解决这个问题,如果我的代码没有意义,我很抱歉,我刚刚开始学习。
DIEA
相关分类