返回的状态更新器函数不会像基于类的组件那样useState合并状态。this.setState()在功能组件中,您必须手动将旧状态与新状态合并。您正在将新Map对象传递给setSearchHistory,因此它将完全覆盖旧状态。Map您可以通过首先将旧对象中的条目复制到新对象中来更新状态Map,然后在状态中添加要添加的新条目。最后,将这个新Map对象传递给setSearchHistory.// copy (shallow) the old map's entries in the new Mapconst updatedMap = new Map(searchHistory); // add the new entry in the 'updatedMap'updatedMap.set(key, value);// update the statesetSearchHistory(updatedMap);
您可以像下面这样实现: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]]));}