簡體   English   中英

React Hooks useEffect 不會使用正確的狀態

[英]React Hooks useEffect won't use the correct state

<Button
    onClick={() => {
        console.log('addedNodes', addedNodes)
        let credentials = //something...
        let nodes = [...addedNodes]
        console.log(addedNodes)
        setCurrentForm(
            {
                ...currentForm,
                credentials: credentials,
                nodes: [...addedNodes],
            }
        )
    }}
</Button>

我有一個按鈕,它使用另一個狀態addedNodes更新currentForm狀態。 每當currentForm更新時,我都會使用useEffect控制台.記錄currentForm

useEffect(() => {
        console.log('currentForm ,,,,,, ', currentForm)
        console.log('addedNodes ,,,,,, ', addedNodes)
    }, [currentForm]);

這將打印出正確的更新狀態。

但是,當我嘗試使用該狀態添加 API 請求時,它會返回到更新之前的狀態。

例如,當我將useEffect更新為

useEffect(() => {
        console.log('currentForm,,,,,, ', currentForm)
        console.log('addedNodes ,,,,,, ', addedNodes)
        console.log('RUNNING POST')
        setLoadingStatus('loading')

        let body = {
            form: currentForm,
        }

        intializeForms()
        let options = {
            headers: header,
            method: 'post',
            mode: 'cors',
            body: JSON.stringify(body),
        }
        console.log('options.body', options.body)

        const urls = ['...'];
        const fetchJson = url => fetch(url, options).then(res => res.json());
        Promise.all(urls.map(fetchJson))
            .then(([result]) => {
               ...
            })
            .catch(err => {
                setLoadingStatus('none')
                console.log(err)
            });

    }, [currentForm]);

console.log('options.body', options.body)打印出舊的currentForm

這很奇怪,因為console.log(currentForm)打印了預期的狀態,但是當我實際將它用於 API 調用時,它又回到了原始表單。

我認為這是因為每次狀態更新時都會調用這個useEffect ,但不確定。

請問有什么幫助嗎?

有問題的代碼片段

 let body = { form: currentForm, } intializeForms() // later bad body.form content

form到達參考currentFrom對象,然后currentFrom被覆蓋在intializeForms() ...這樣JSON.stringify(body)上的壞數據進行操作。

為什么 Kaca992 的解決方案不起作用?

 let body = { form: {...currentForm}, }

它應該從currentForm的元素/屬性創建一個新對象。
可能它適用於currentForm某些部分, fe 用於nodes因為它們被正確(以不可變的方式 - 通過新實例)分配/傳遞:

 nodes: [...addedNodes],

可能其他currentForm元素是始終相同對象引用的副本,在更改時發生變異,而不是用新實例替換。

解決方案:

在這種情況下,在currentForm “消耗”(字符串化)之后調用intializeForms()就足夠了 - let options = block。

其它好去處形式復位( intializeForms()調用)可以Promise.all(...解析功能( .then部分)。

initializeForms 有什么作用? 如果 currentForms 是引用類型,您可能會重置該值? 嘗試像這樣設置主體:

    let body = {
        form: {...currentForm},
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM