按下等待函数完成,然后在React Native中继续



我的代码同步有问题,我的程序在第二次按下按钮时会做出反应,就像第一次按下按钮一样。(在底部详细解释(。

我有以下Firebase API函数:

export const noOpponent = (Key, setOpponent) => {
console.log("key: " + Key)
duettsRef
.where("key", "==", Key)
.where("player1", "!=", firebase.auth().currentUser.uid)
.where("player2", "==", "")
.limit(1)
.get()
.then((querySnapshot) => {
setOpponent(!querySnapshot.empty)
console.log("QuerysnapshotResult: " + !querySnapshot.empty)
})
};

现在我得到了另一个.js文档,其中包括以下代码(缩写(:

const DuellScreen = () => {
const [opponent, setOpponent] = useState(null);
return (
...
<BlockButton
text="Apply"
onPress={() => {
noOpponent(code, setOpponent);
console.log("OPPONENT:" + opponent),
opponent ? (
opponent == true?(
setKeyToDuett(code),
Platform.OS === "android"?(
ToastAndroid.show("Game joined!", ToastAndroid.SHORT)):
(Alert.alert("Game joined!"))
):(
Platform.OS === "android"?(
ToastAndroid.show("Game does not exist or someone else has already joined!", ToastAndroid.SHORT)):
(Alert.alert("Game does not exist or someone else has already joined"))
)
):(
console.log("opponent is probably null")
)}
}  
/>
...
)

现在,第一次按下我的按钮,我就会打印出以下行:

OPPONENT:null
opponent is probably null
QuerysnapshotResult: true

按下第二个按钮,我得到:

OPPONENT:true
QuerysnapshotResult: true

第二次按下按钮的结果,是我预期的第一次按下按钮已经得到的结果。。。我认为,在调用noOpponent(code, setOpponent);之后,它只是立即跳到下一行(opponent ? (...,对手仍然为空,因为它没有等待我的opponentnoOpponent function的结果/更改。在第二个按钮上按下它然后设置为true,因为第一个按钮按下了。并在console.log("QuerysnapshotResult: " + !querySnapshot.empty)之前打印出console.log("OPPONENT:" + opponent)

我如何正确地同步,我的程序正在等待noOpponent函数的结果,该函数正确地设置了opponent,然后跳到此行opponent ?(

您需要使用异步方法或Promise,请尝试

export const noOpponent = (Key, setOpponent) => {
console.log("key: " + Key)
duettsRef
.where("key", "==", Key)
.where("player1", "!=", firebase.auth().currentUser.uid)
.where("player2", "==", "")
.limit(1)
.get()
.then((querySnapshot) => {
setOpponent(!querySnapshot.empty)
console.log("QuerysnapshotResult: " + !querySnapshot.empty)
})

};

然后按下按钮。

onPress={async () => {
await noOpponent(code, setOpponent);
console.log("OPPONENT:" + opponent),
opponent ? (
opponent == true ? (
setKeyToDuett(code),
Platform.OS === "android"?(
ToastAndroid.show("Game joined!", ToastAndroid.SHORT)):
(Alert.alert("Game joined!"))
):(
Platform.OS === "android"?(
ToastAndroid.show("Game does not exist or someone else has already joined!", ToastAndroid.SHORT)):
(Alert.alert("Game does not exist or someone else has already joined"))
)
):(
console.log("opponent is probably null")
)}
}  

最新更新