Reactjs 钩子:更新地图的值 [英] Reactjs hooks: update value of map

查看:46
本文介绍了Reactjs 钩子:更新地图的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 reactjs 的新手,这就是为什么它对你来说很幼稚.

我需要更新其键未知的映射的值.

I need to update the value of a map in which its keys are unknown.

  const App = () => {
    const [storeMap, setStoreMap] = useState(new Map());
    let _tmpMap = new Map();
    return (<>
    {Object.keys({ key1: "hey", key2: "you" }).map((item) => {
          return (
            <button
              value={item}
              key={item}
              onClick={(e) => {
                _tmpMap.set(item, e.target.value);
           
                console.log(..._tmpMap); // {1}
                setStoreMap(_tmpMap);
              }}
            >
              {item}
            </button>
          );
          //   return <i key={item}>KJ </i>;
        })}
  </>)
   
  }

点击两个按钮后,我希望在上面的代码中看到的是:

What I am expecting to see in the above code after clicking both buttons is:

  /*    {1}    */ 
  console.log(..._tmpMap)
  //i expect this: {key1:"key1" , key2:"key2"}

我在现实中看到的是 {key1:"key1"} 在按下 key 1{ key2:"key2"} 之后> 按键 2

What I see in reality is {key1:"key1"} after pressing key 1 and { key2:"key2"} after pressing key 2

我的问题是:

如何更新 storeMap,同时保留其以前的条目?

How can I update storeMap while preserving its previous entries?

这是代码

推荐答案

storeMap.set() 更新地图并 setStoreMap 设置状态.

storeMap.set() updates the map and setStoreMap sets the state.

React 比较新旧 Map 的引用,在这种情况下,它们共享相同的值.如果你想让 React 知道"关于更新,您需要将 Map 的副本传递给 setStoreMap,而不是旧引用的副本,您可以通过创建新 Map 来实现.我相信你可以放弃使用 _tmpMap.

React compares the references of the new and old Map which, in this case, share the same value. If you want React to "know" about the update you will need to pass to setStoreMap a clone of the Map instead of a copy of the old reference, you can do that by creating a new Map. I believe you can drop the use of _tmpMap.

const App = () => {
    const [storeMap, setStoreMap] = useState(new Map());

    const updateStoreMap = (k, v) => {
        // pass a clone of storeMap
        setStoreMap(new Map(storeMap.set(k, v)));
    };
    
    return (
        <>
            {Object.keys({ key1: 'hey', key2: 'you' }).map((item) => {
                return (
                    <button
                        value={item}
                        key={item}
                        onClick={(e) => {
                            updateStoreMap(item, e.target.value);
                        }}
                    >
                        {item}
                    </button>
                );
                //   return <i key={item}>KJ </i>;
            })}
        </>
    );
};

这篇关于Reactjs 钩子:更新地图的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆