addDoc从firestore v9在状态更改之前运行。

huangapple go评论83阅读模式
英文:

addDoc from firestore v9 is running before the state changes

问题

const [workout, setWorkout] = useState({
    workoutname: "",
    exercisesSelection: [],
});

const SaveWorkout = async () => {
    setWorkout(prevArr => {
        return {
            ...prevArr,
            workoutname: workoutName,
            exercisesSelection: currentExercises
        }
    })
    console.log(workout)
    await addDoc(workoutsCollectionRef, {
        workoutName: workout.workoutname,
        exercises: workout.exercisesSelection,
    })
}

文档添加时使用了空值。我认为在 addDoc 后状态发生了变化。

英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const [workout,setWorkout] = useState({
      workoutname:&quot;&quot;,
      exercisesSelection:[],
    });
    
const SaveWorkout = async ()=&gt;{
      setWorkout(prevArr=&gt;{
        return {
          ...prevArr,
          workoutname:workoutName,
          exercisesSelection:currentExercises
        }
      })
      console.log(workout)
      await addDoc(workoutsCollectionRef,{
        workoutName:workout.workoutname,
        exercises:workout.exercisesSelection,
      })
      
    }

<!-- end snippet -->

Documment is being added with the values empty. I believe that the state is changing after the addDoc.

addDoc从firestore v9在状态更改之前运行。

答案1

得分: 1

设置状态是ReactJS中的异步操作。如果您有一个操作只应在状态已被修改后运行,请为其使用一个(独立的)useEffect钩子。所以像这样:

useEffect(() => {
  await addDoc(workoutsCollectionRef,{
    workoutName: workout.workoutname,
    exercises: workout.exercisesSelection,
  }), 
  [workout] // &#128072; 确保代码在workout更改时运行
);

请注意,这与特定的Firebase版本无关,对于SDK版本8及之前的版本也是相同的。

另请参阅:

英文:

Setting state is an asynchronous operation in ReactJS. If you have an operation that should only run after the state has been modified, use a (separate) useEffect hook for it. So something like:

useEffect(() =&gt; {
  await addDoc(workoutsCollectionRef,{
    workoutName:workout.workoutname,
    exercises:workout.exercisesSelection,
  }), 
  [workout] // &#128072; ensure the code runs whenever workout has changed
);

Note that this is not related to the specific Firebase version, and would be the same in SDK versions 8 and before

Also see:

huangapple
  • 本文由 发表于 2023年7月11日 05:07:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/76657346.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定