我正在嘗試創建需要某種 n-back 功能的東西。在這里,我重新創建了類似的文本,顯示在隨機框中,然后再次顯示在隨機框中,它應該告訴您它是否與前一個框相同(或與之前的許多框相同)它設定為)。
我正在使用一個陣列,并將我推送到陣列中第 0 個索引的當前框與前一個框(第 1 個索引)進行比較。
這對我來說在香草 Javascript 中效果很好。但是在 React Native 中,我真的不明白發生了什么。
https://snack.expo.dev/@skjones90/58123f
import React, { useState } from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';
export default function App() {
const [box, setBox] = useState(0)
const [same, setSame] = useState("")
const [boxesArr, setBoxesArr] = useState([])
const [hasStarted, setHasStarted] = useState(false)
function start() {
setHasStarted(true)
let num = Math.floor(Math.random() * (3 - 1 1) ) 1;
setBox(num)
setBoxesArr((prev) => {
return [num, ...prev]
})
checkPrevious()
}
function checkPrevious() {
if (boxesArr[0] === boxesArr[1]) {
setSame("Yes")
} else {
setSame("No")
}
setTimeout(clearBox, 1000)
}
function clearBox() {
setBox(0)
setTimeout(start, 500)
}
return (
<View style={styles.container}>
<Text>Same as previous? {same}</Text>
<View style={styles.boxes}>
<View style={{
width: 100,
height: 100,
backgroundColor: "blue"
}}>
<Text style={styles.paragraph}>
{box === 1 ? "Here" : null}
</Text>
</View>
<View style={{
width: 100,
height: 100,
backgroundColor: "red"
}}>
<Text style={styles.paragraph}>
{box === 2 ? "Here" : null}
</Text>
</View>
<View style={{
width: 100,
height: 100,
backgroundColor: "orange"
}}>
<Text style={styles.paragraph}>
{box === 3 ? "Here" : null}
</Text>
</View>
</View>
<TouchableOpacity onPress={() => {hasStarted === false ? start() : null}}>
<View style={{backgroundColor: "purple", width: 100, marginTop: 10}}>
<Text style={{textAlign: "center", color: "white"}}>
Start
</Text>
</View>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: "center",
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
paddingLeft: 8,
paddingRight: 8,
paddingTop: 10
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
boxes: {
flexDirection: "row"
}
});
我認為問題源于“checkPrevious”函式中的比較。
uj5u.com熱心網友回復:
你的問題是:
setBoxesArr((prev) => {
return [num, ...prev]
});
不會boxesArr立即改變你的。只有在組件的下一次渲染中boxesArr才會保存您設定的新值。這意味著當您呼叫時checkPrevious(),boxesArr 仍然是舊值,而不是您剛剛設定的值。由于same狀態是從你的 派生的boxesArr,我建議洗掉checkPrevious()函式和same狀態,而是在你的組件的渲染上計算它:
const same = boxesArr[0] === boxesArr[1] ? "Yes" : "No";
請參見此處的示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/522563.html
