【问题标题】:React Native state not updating through useSate Methed of ReactReact Native 状态不通过 React 的 setState 方法更新
【发布时间】: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


    【解决方案1】:

    我相信您正在尝试访问尚未更新的变量,因为您尝试在同一范围内获取更新的代码。 你可以做一个简单的测试来看看这是否是问题,将你的代码更改为这样的:

    const getCounter = async () => {
            let newCounter = null
    
            try {
                const querySnap = await fireStore().collection('Counter').doc('count').get()
                newCounter = (querySnap.data().counter)+1
            } catch(error) {
                alert("Something went wrong\n[Error]: "+ error)
            }
            try {
                setCounter(newCounter)
                await fireStore().collection('Counter').doc("count").update({
                    counter: newCounter
                })
            } catch {
                // alert("Something went wrong\nPlease try again...")
            }
        }
    

    这样您就可以保证您传递给 firebase 的值是在发送前实时计算的。

    【讨论】:

      【解决方案2】:

      我相信您的问题在于 setCounter 是异步运行的,并且不会返回您可以与 async/await 一起使用的承诺。在您的情况下,getCounter 被调用,触发setCounter 函数,然后在setCounter 更新counter 的值之前将counter 发送到firebase。

      我能想到的最好的解决方案是使用useEffect,因为它可以用来监控计数器的值,然后在更新时触发函数调用。因此,您可以执行以下操作:

      
      const YourElement = () => {
         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...")
              }
          }
      
         const postData = async () => {
              if (!adTitle || !adDescription || !yearOfPurchase || !price || !contactNo) {
                  Alert.alert("Please fill all the Fields")
                  return
              }
      
              try {
                  getCounter()
                  Alert.alert("Item Successfully Posted..")
                  setAdTitle('')
                  setAdDescription('')
                  setYearOfPurchase('')
                  setPrice('')
                  setContactNo('')
                  setImage('')
              } catch (err) {
                  Alert.alert("Something went wrong\nPlease try again...")
              }
      
      }
      
         useEffect(()=>{
            fireStore().collection("ads").add({
                adTitle,
                adDescription,
                yearOfPurchase,
                price,
                contactNo,
                image,
                uniqueID: counter,
                uid: Auth().currentUser.uid
                })},[counter])
      
         return <ChildElements/>
      }
      

      这样数据只会在counter 更新后才会发送到firebase。

      【讨论】:

      • 谢谢兄弟,你的逻辑对我不起作用,但它可以帮助我找出实际问题。现在问题已经解决了......再次感谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2020-01-16
      • 1970-01-01
      相关资源
      最近更新 更多