[英]How to add value to Map initialized in state using react?
I have application and i need to keep search history, in my opinion Map
is suitable here:我有应用程序,我需要保留搜索历史,我认为
Map
适合这里:
const [searchHistory, setSearchHistory] = useState(new Map());
to update it use setSearchHistory(new Map([[text, result.repos]]));
更新它使用
setSearchHistory(new Map([[text, result.repos]]));
but it replaces Map with new Map, could you please tell me how can i add value to Map initialized in state ?但它用新的 Map 替换了 Map,你能告诉我如何为状态初始化的 Map 添加值吗?
State updater function returned by useState
doesn't merges the state like this.setState()
in class-based components. useState
返回的状态更新器函数不会像基于类的组件中的this.setState()
那样合并状态。 In functional components, you have to manually merge the old state with the new state.在功能组件中,您必须手动将旧状态与新状态合并。
You are passing the new Map
object to setSearchHistory
, so it will completely overwrite the old state.您将新的
Map
对象传递给setSearchHistory
,因此它将完全覆盖旧状态。
You could update the state by first copying the entries in the old Map
object in to new Map
object, then add the new entry you want to add in the state.您可以通过首先将旧
Map
对象中的条目复制到新Map
对象中,然后添加要添加到状态中的新条目来更新状态。 Finally, pass this new Map
object to setSearchHistory
.最后,将这个新的
Map
对象传递给setSearchHistory
。
// copy (shallow) the old map's entries in the new Map
const updateMap = new Map(searchHistory);
// add the new entry in the 'updatedMap'
updatedMap.set(key, value);
// update the state
setSearchHistory(updatedMap);
You can achieve that like the following:您可以通过以下方式实现:
const [searchHistory, setSearchHistory] = useState(new Map());
function onChange(key, value) {
// change the searchHistory map with a new Map from the current searchHistory, and the new key, value
setSearchHistory(new Map([...searchHistory, [key, value]]));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.