【发布时间】:2021-05-20 12:46:40
【问题描述】:
我的代码同步出现问题,我的程序在第二次按下按钮时会做出反应,就像在第一次按下按钮时一样。 (在底部详细解释)。
我有以下 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 ? (...,对手仍然为空,因为它没有等待我的opponent 从noOpponent function 的结果/更改。在第二个按钮上按下它然后设置为真,因为第一个按钮按下。
并且在console.log("QuerysnapshotResult: " + !querySnapshot.empty)之前打印出console.log("OPPONENT:" + opponent)
我怎样才能正确同步这个,我的程序正在等待 noOpponent 函数的结果,该函数正确设置 opponent 然后跳转到这一行 opponent ? (
【问题讨论】:
-
使用 promise 来实现。
-
@DipanSharma 我已经尝试过了,但我仍然得到 OPPONENT:... 在 QuerysnapshotResult: ... 之前打印出来:...所以它仍然无法正常工作
标签: reactjs firebase react-native google-cloud-firestore