代码之家  ›  专栏  ›  技术社区  ›  Mistakamikaze

React Redux |在全局Redux状态之前更新本地状态

  •  0
  • Mistakamikaze  · 技术社区  · 2 年前

    我正在尝试创建一个包含表单的页面,该表单在提交时会显示消息。

    • 提交此表单时,将根据表单中的内容显示消息。
    • 消息是通过将表单的内容分派到我的redux操作来创建的,该操作执行一些逻辑,然后通过我的reducer更新我的redux存储。
    • 然后,前端通过以下方式检查存储区中的消息 useEffect() 。但是,它仅基于跟踪表单是否被单击的局部状态变量检查消息(以便停止无限次重新呈现)。

    这是我到目前为止所做的

    import reduxAction from "somewhere"
    
    function page() {
        const reduxState = useSelector((state) => state.someGlobalState);
        const [localIndicator, setLocalIndicator] = useState(false); // tracks if form was submitted
        const [message, setMessage] = useState("")
    
        const onSubmit = async(formData) => {
            dispatch(reduxAction(formData))
            setLocalIndicator(true) // update the local indicator when the form is clicked
        }
    
        useEffect( () => {
            /* After I click the form, the local indicator updates to true
               so the message is updated. THE ISSUE IS the reduxState has not yet been updated!
               By the time it updates, this has already happened and so im displaying the old message
               not the new one
            */
            if (setLocalIndicator === true){
                setMessage(reduxState.message)
                setLocalIndicator(false) // to prevent infinite re-renders
            }
        })
    
        return(
            <Form onSubmit=onSubmit>
                ...
            {message}
        )
    
    
    }
    

    目前它不起作用,因为在我提交表单并发送表单数据后,本地状态指示器会更新,但redux状态之前不会更新 useEffect() 运行,因此过早地重新渲染表单( useEffect() 应仅在redux状态更新后运行,或者本地状态指示器应仅在redux状态更新后更新。

    任何帮助都将不胜感激。

    1 回复  |  直到 2 年前
        1
  •  1
  •   ourmaninamsterdam    2 年前

    您需要添加 reduxState.message localIndicator 到useEffect的dependencies数组,以便它知道在发生更改时进行更新。当前,useEffect将在每个渲染周期上运行,这并不理想:

    useEffect( () => {
            /* After I click the form, the local indicator updates to true
               so the message is updated. THE ISSUE IS the reduxState has not yet been updated!
               By the time it updates, this has already happened and so im displaying the old message
               not the new one
            */
            if (setLocalIndicator === true){
                setMessage(reduxState.message)
                setLocalIndicator(false) // to prevent infinite re-renders
            }
        },[localIndicator, reduxState.message])