反应归还 |在全局 redux 状态之前更新本地状态

React Redux | local state updating before global redux state

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

这是我到目前为止所做的

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() 运行s 之前没有更新,所以表单是过早重新渲染(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])