2 回答

TA貢獻1810條經驗 獲得超4個贊
返回的狀態更新器函數不會像基于類的組件那樣useState合并狀態。this.setState()在功能組件中,您必須手動將舊狀態與新狀態合并。
您正在將新Map對象傳遞給setSearchHistory,因此它將完全覆蓋舊狀態。
Map您可以通過首先將舊對象中的條目復制到新對象中來更新狀態Map,然后在狀態中添加要添加的新條目。最后,將這個新Map對象傳遞給setSearchHistory.
// copy (shallow) the old map's entries in the new Map
const updatedMap = new Map(searchHistory);
// add the new entry in the 'updatedMap'
updatedMap.set(key, value);
// update the state
setSearchHistory(updatedMap);

TA貢獻1804條經驗 獲得超3個贊
您可以像下面這樣實現:
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]]));
}
添加回答
舉報