This link gets close to the issue, 但我有一个我无法弄清楚的用例。场景如下:
我有一个带有状态变量和引用的组件:
const [siteTextToUpdate, setSiteTextToUpdate] = useState({});
const [addLoad, setAddLoad] = useState(false);
const siteTextRef = useRef()
siteTextRef.current = siteTextToUpdate;
然后我有一个清理效果来在卸载时触发 redux 操作:
useEffect(() => {
return () => {
console.log("unmounting: ");
console.log(siteTextRef.current);
if (JSON.stringify(siteTextRef.current) !== '{}') {
setStaticSiteText(siteTextRef.current); // <=== RDX action
}
}
}, [])
然后,我将使用 setSiteTextToUpdate({...randomData})
然后,我将使用以下更新本地状态和更新 redux 状态的函数更新状态:
function handleAddCard() {
let confirmed = window.confirm('Adding a metal will cause the page to reload, and you will lose any existing changes. Continue?')
let purpose = 'addNewCard'
if (confirmed) {
setAddLoad(true); // <===== this does!
setSiteTextToUpdate({}); // <===== this does not update!
axios
.patch((BACKEND + '/admin/text'), { purpose, newCardTitle })
.then(res => {
if (res.data.success) {
setStaticSiteText(res.data.siteText) // <==== RDX state setter
} else {
FAIL_CONFIG.message = res.data.msg;
store.addNotification(FAIL_CONFIG)
}
})
.catch(e => console.log(e))
}
}
siteTextToUpdate
addCard()
和 setSiteTextToUpdate
到 {}
siteTextRef.current
清除函数中的值未重置!