英文:
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:"",
exercisesSelection:[],
});
const SaveWorkout = async ()=>{
setWorkout(prevArr=>{
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.
答案1
得分: 1
设置状态是ReactJS中的异步操作。如果您有一个操作只应在状态已被修改后运行,请为其使用一个(独立的)useEffect
钩子。所以像这样:
useEffect(() => {
await addDoc(workoutsCollectionRef,{
workoutName: workout.workoutname,
exercises: workout.exercisesSelection,
}),
[workout] // 👈 确保代码在workout更改时运行
);
请注意,这与特定的Firebase版本无关,对于SDK版本8及之前的版本也是相同的。
另请参阅:
- https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately
- https://stackoverflow.com/questions/54119678/is-usestate-synchronous
- https://stackoverflow.com/questions/67614272/await-usestate-in-react
英文:
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(() => {
await addDoc(workoutsCollectionRef,{
workoutName:workout.workoutname,
exercises:workout.exercisesSelection,
}),
[workout] // 👈 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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论