如何匹配ID切换布尔值并合并数组?React代码优化求助
Solution
Issues with Your Current Code
- Misuse of
reduce: You’re usingreducefor side effects (modifying thedataarray) instead of its intended purpose of accumulating a value. - Direct state mutation: Assigning
data = data.map(...)modifies the original array, which violates React’s immutability rules ifdatais a state variable. - Incorrect object replacement: When a match is found, you replace the entire object with the string
'aaa'instead of updating thetoggleproperty.
Correct Implementation
useEffect(() => { // Parse favorite history from localStorage const storedFavorites = localStorage.getItem('FavoriteHistory'); const localFavorites = storedFavorites ? JSON.parse(storedFavorites) : []; // Create a lookup map for efficient ID-to-value checks const favoriteValueMap = new Map( localFavorites.map(fav => [fav.id, fav.value]) ); // Generate updated data by syncing toggle values with local favorites const updatedData = data.map(item => ({ ...item, // Use local favorite value if available, else keep original toggle toggle: favoriteValueMap.has(item.id) ? favoriteValueMap.get(item.id) : item.toggle })); // Update your state with the new dataset (use your state setter here) // setData(updatedData); }, [data]);
How It Works
- Retrieve Local Data: Fetch and parse
FavoriteHistoryfrom localStorage, defaulting to an empty array if it doesn’t exist. - Build Lookup Map: Convert the local favorites array into a
Mapfor O(1) ID lookups, making the process efficient even with large datasets. - Update Data Array: Use
mapto create a new immutable array. For each item:- Check if its ID exists in the lookup map.
- If it does, set
toggleto the corresponding value from local storage. - If not, retain the original
togglevalue.
- Sync State: Assign the new array to your state variable using your state setter (e.g.,
setData).
Alternative: Toggle Existing Value (If Required)
If you want to flip the existing toggle value whenever a matching ID is found in local storage (ignoring the value property), use this version:
const updatedData = data.map(item => { const hasMatch = localFavorites.some(fav => fav.id === item.id); return { ...item, toggle: hasMatch ? !item.toggle : item.toggle }; });
内容的提问来源于stack exchange,提问作者Canadian Lonman
相关产品推荐
相关产品推荐

