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

React Redux Reducer异常求助:实现单选激活状态切换功能

Fixing Radio-Style Active Selection in Your Reducer

Got it, let's sort out this single-selection (radio button style) active state issue in your reducer. The problem with your current code is that you're only toggling the clicked item's active status, but you aren't resetting all other items' active to false—that's why you end up with multiple items marked as active.

Here's the corrected reducer case that implements the single-selection behavior you need:

case actionTypes.SET_ACTIVE:
  const updatedAccounts = accounts.map((item) => {
    // Set active to true only for the clicked item, false for all others
    return item.id === action.id 
      ? { ...item, active: true } 
      : { ...item, active: false };
  });
  console.log(updatedAccounts);
  return { ...state, accounts: updatedAccounts };
default:
  return state;

How this works:

  • We use map() to iterate over every item in the accounts array (this is the right tool here, since we need to update every item's state, not just filter or modify one).
  • For each item:
    • If it's the item that was clicked (matches action.id), we return a copy of the item with active: true.
    • For every other item, we return a copy with active: false.
  • This ensures only one item is ever marked as active at a time, exactly like a radio button group.

If you later want the option to deselect the currently active item by clicking it again, you can adjust the logic slightly:

case actionTypes.SET_ACTIVE:
  const updatedAccounts = accounts.map((item) => {
    if (item.id === action.id) {
      // Toggle active if clicking the already selected item
      return { ...item, active: !item.active };
    } else {
      // Keep other items inactive unless we're deselecting the current one
      return { ...item, active: false };
    }
  });
  console.log(updatedAccounts);
  return { ...state, accounts: updatedAccounts };
default:
  return state;

But based on your original request, the first snippet is exactly what you need for strict single-selection.

内容的提问来源于stack exchange,提问作者Nika Roffy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 19:07:47