繁体   English   中英

反应还原 | 全局 redux 状态之前的本地状态更新

[英]React Redux | local state updating before global redux state

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

  • 提交此表单时,会根据表单中的内容显示一条消息。
  • 该消息是通过将表单的内容分派给我的 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 状态更新后更新。

任何帮助将不胜感激。

您需要将reduxState.messagelocalIndicator添加到 useEffect 的依赖项数组中,以便它知道在更改时进行更新。 目前您的 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])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM