为什么我的 useRef 绑定到状态不更新?

时间:2021-03-11 14:59:27

标签: javascript reactjs react-redux

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))
    }
}

执行顺序:

  1. 更新局部状态变量siteTextToUpdate
  2. addCard()setSiteTextToUpdate{}
  3. 使用 axios 发出 http 请求,并触发 redux 操作
  4. 组件卸载和清理
  5. siteTextRef.current 清除函数中的值未重置!

为什么 ref.current 值不反映状态变化?

0 个答案:

没有答案