簡體   English   中英

useState 掛鈎無法更新 map

[英]useState hook not working on updating map

我正在使用 useState 掛鈎來存儲 Map

    const [optionList, setOptionsList] = useState(new Map([
        [
            uuidv1(), {
                choice: "",
            }
        ]
    ]));

在添加新選項時,我稱之為 function

    const handleAddNewOption = () => {
        console.log('reached here');
        optionList.set(uuidv1(), {
            choice: "",
        });
    }

但列表不會在更新時重新呈現

    useEffect(() => {
    console.log("optionList", optionList)    
}, [optionList]);

您需要檢索條目數組,然后將新條目添加到其中,最后構造一個全新的 Map。

const handleAddNewOption = () => {
    console.log('reached here');
    const entries = [
        ...optionList.entries(),
        [
            uuidv1(),
            { choice: "" }
        ]
    ];
    setOptionsList(new Map(entries));
}

您還可以考慮使用useState的回調形式,這樣您就不會在每次渲染時不必要地創建一個新的未使用的 Map。

要考慮的另一個選項是使用由 uuid 索引的 object 而不是 Map,如果只是為了便於編碼 - 使用帶有 React 的 Maps 比理想情況下要復雜一些。

React shallow 比較舊的 state 和新的 state 值來檢測是否有變化。 由於它是相同的 Map (地圖的項目沒有比較),React 忽略更新。

您可以從舊的 Map 創建一個新的 Map,然后對其進行更新:

 const { useState, useEffect } = React; const uuidv1 = () => Math.random(); // just for the demo const Demo = () => { const [optionList, setOptionsList] = useState(new Map([ [ uuidv1(), { choice: "", } ] ])); const handleAddNewOption = () => { console.log('reached here'); setOptionsList(prevList => { const newList = new Map(prevList); newList.set(uuidv1(), { choice: "", }); return newList; }); }; useEffect(() => { console.log("optionList", JSON.stringify([...optionList])); }, [optionList]); return ( <button onClick={handleAddNewOption}>Add</button> ); } ReactDOM.render( <Demo />, root );
 <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div id="root"></div>

暫無
暫無

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

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