[英]React Redux | local state updating before global redux state
I'm trying to create a page that contains a form that when submitted displays a message.我正在尝试创建一个包含表单的页面,该表单在提交时会显示一条消息。
useEffect()
.useEffect()
检查存储中的消息。 However it only checks for the message based on a local state variable that keeps track of whether the form was clicked (so as to stop infinite re-renders). Here is what I've done so far这是我到目前为止所做的
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}
)
}
Currently it's not working because after I submit the form and dispatch the form data, the local state indicators update BUT the redux state does not update before useEffect()
runs and so the form is re-rendered too early ( useEffect()
should only run after the redux state updates or the local state indicator should only update after the redux state updates.目前它不起作用,因为在我提交表单并发送表单数据后,本地状态指示器更新但 redux 状态在
useEffect()
运行之前没有更新,因此表单重新渲染太早( useEffect()
应该只运行在 redux 状态更新后或本地状态指示器应该只在 redux 状态更新后更新。
Any help would be greatly appreciated.任何帮助将不胜感激。
You need to add reduxState.message
and localIndicator
to the dependencies array of useEffect so that it knows to update when that changes.您需要将
reduxState.message
和localIndicator
添加到 useEffect 的依赖项数组中,以便它知道在更改时进行更新。 Currently your useEffect will run on every render cycle, which is not ideal:目前您的 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.