如果一个函数更新状态而另一个函数紧接着访问该状态,是否会导致竞争条件?

If a function updates state and another function accesses the state immediately afterwards, would it result in a race condition?

我有两个组件,一个是上传文件,另一个是可以提交的表单。上传者在上传完成时有回调,表单在提交时有回调。我的目标是在上传者完成上传并提交表单时向后端发出请求,而不关心哪个先发生。

我目前的解决方案是这样的:

const [isFileUploaded, setFileUploaded] = useState(false);
const [isFormSubmitted, setFormSubmitted] = useState(false);

const handleUploadFinish = ( {signedBlobId} ) => {
    // update params to be sent to the backend with the signedBlobId

    setFileUploaded(true)

    if (isFormSubmitted) {
        // make the backend call
    }
}

const handleFormSubmitted = (values) => {
    // update params to be sent to the backend with the values

    setFormSubmitted(true)

    if (setFileUploaded) {
        // make the backend call
    }
}

但是,我在 the React documentation on state 中读到设置状态是一个异步操作。这让我担心,如果两个回调恰好几乎同时被调用,那么检查时 isFileUploadedisFormSubmitted 可能仍然是 false,防止后端调用发生。

这是一个合理的担忧吗?如果是这样,有什么更好的处理方法?

是的,按照您构建逻辑的方式,可能会出现竞争条件。您应该希望您的代码具有更同步的模式。幸运的是,有一种方法可以通过集成 useEffect() 钩子来解决这个问题。本质上,只要您订阅的值发生变化,它就会被触发。

在这种情况下,我们要验证 isFileUploadedisFormSubmitted 都为真,然后我们才会进行最终的后端 API 调用。

考虑这样一个例子:

import React, { useState, useEffect } from "react"

const myComponent = () => {

    const [isFileUploaded, setFileUploaded] = useState(false);
    const [isFormSubmitted, setFormSubmitted] = useState(false);
    const [params, setParams] = useState({})

    const handleUploadFinish = ( {signedBlobId} ) => {
        // update params to be sent to the backend with the signedBlobId
        setFileUploaded(true)
    }

    const handleFormSubmitted = (values) => {
        // update params to be sent to the backend with the values
        setFormSubmitted(true)
    }

    useEffect(() => {
        if(isFormSubmitted && isFileUploded){
           ...make backend call with updated params
        }
    }, [isFormSubmitted, isFileUploaded])

   return(
      ....
   )
}