admin管理员组

文章数量:1025244

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

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

本文标签: javascriptuseState hook not working on updating mapStack Overflow