You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何匹配ID切换布尔值并合并数组?React代码优化求助

Solution

Issues with Your Current Code

  • Misuse of reduce: You’re using reduce for side effects (modifying the data array) 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 if data is a state variable.
  • Incorrect object replacement: When a match is found, you replace the entire object with the string 'aaa' instead of updating the toggle property.

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

  1. Retrieve Local Data: Fetch and parse FavoriteHistory from localStorage, defaulting to an empty array if it doesn’t exist.
  2. Build Lookup Map: Convert the local favorites array into a Map for O(1) ID lookups, making the process efficient even with large datasets.
  3. Update Data Array: Use map to create a new immutable array. For each item:
    • Check if its ID exists in the lookup map.
    • If it does, set toggle to the corresponding value from local storage.
    • If not, retain the original toggle value.
  4. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 09:31:33