【发布时间】:2021-04-18 02:53:54
【问题描述】:
我的代码中似乎有什么问题, 我正在创建一个基于 firestore 和 firebase 的应用程序。 到目前为止一切正常但现在我想添加一个唯一的键,从 1 开始,然后按升序到 每个firebase 中的我的项目,我可以通过它检索我的 FlatList 组件中的所有项目。 但我无法做到这一点。 我目前面临的一个问题是,当用户填写表单并单击 POST Button**[POST Button 的详细信息如下]** 数据为存储在 Firebase 但计数器 没有增加,之后 第二次尝试(指用户填写另一个表单并单击 POST 按钮) 最终增加的值。
表示在两个表单填写后,计数器递增一,但我想在每个填写的表单上递增计数器。。 p>
请帮帮我!
查看下面的代码
const [adTitle, setAdTitle] = useState('')
const [adDescription, setAdDescription] = useState('')
const [yearOfPurchase, setYearOfPurchase] = useState('')
const [price, setPrice] = useState('')
const [contactNo, setContactNo] = useState('')
const [image, setImage] = useState('')
const [counter, setCounter] = useState(0)
我在我的应用程序中使用这些赌注,所有其他工作正常问题都出现在这个问题上。
const [counter, setCounter] = useState(0)
并在用户按下发布按钮时调用此函数
const postData = async () => {
if (!adTitle || !adDescription || !yearOfPurchase || !price || !contactNo) {
Alert.alert("Please fill all the Fields")
return
}
try {
getCounter(); // <-- called this function for Counter, Details are Below
await fireStore().collection("ads").add({
adTitle,
adDescription,
yearOfPurchase,
price,
contactNo,
image,
uniqueID: counter,
uid: Auth().currentUser.uid
})
Alert.alert("Item Successfully Posted..")
setAdTitle('')
setAdDescription('')
setYearOfPurchase('')
setPrice('')
setContactNo('')
setImage('')
} catch (err) {
Alert.alert("Something went wrong\nPlease try again...")
}
}
在调用getCounter(); 函数时,它是获取当前计数器值从firebase然后将该值增加一 然后更新 firebase 中的值
getCounter(); 函数的代码:(我认为问题就在这个 getCounter() 中,但我无法弄清楚。)
const getCounter = async () => {
try {
const querySnap = await fireStore().collection('Counter').doc('count').get()
setCounter((querySnap.data().counter)+1)
} catch(error) {
alert("Something went wrong\n[Error]: "+ error)
}
try {
await fireStore().collection('Counter').doc("count").update({
counter: counter
})
} catch {
// alert("Something went wrong\nPlease try again...")
}
}
【问题讨论】:
标签: react-native use-state react-native-state