最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - useState hook not working on updating map - Stack Overflow

matteradmin6PV0评论

I am using a useState hook to store a Map

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

on adding a new option , I call this function

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

but the list does not re-render on updation

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

I am using a useState hook to store a Map

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

on adding a new option , I call this function

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

but the list does not re-render on updation

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

Share Improve this question asked Mar 8, 2021 at 6:30 Kuldeep SharmaKuldeep Sharma 211 silver badge3 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

You'll need to retrieve the array of entries, then add the new entry to it, and finally construct an entirely new Map.

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

You also might consider using the callback form of useState so you don't unnecessarily create a new unused Map every render.

Another option to consider is to use an object indexed by uuid instead of a Map, if only for the ease of coding - using Maps with React is a bit more plicated than would be ideal.

React shallow pares the old state and the new state values to detect if something changed. Since it's the same Map (Map's items are not pared), React ignores the update.

You can create a new Map from the old one, and then update it:

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./react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg./react-dom@17/umd/react-dom.development.js"></script>

<div id="root"></div>

Leverage the fact that useState can take a function. This function gives you the previous value and it's supposed to return the new value for the state

const [myMap, setMyMap] = useState(new Map())

setMyMap((prevMap) => {
    const nextMap = new Map(prevMap);
    nextMap.set(key, value);
    return nextMap;
});
Post a comment

comment list (0)

  1. No comments so far