[英]React Redux | local state updating before global redux state
我正在嘗試創建一個包含表單的頁面,該表單在提交時會顯示一條消息。
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.message
和localIndicator
添加到 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.