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 theaccountsarray (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 withactive: true. - For every other item, we return a copy with
active: false.
- If it's the item that was clicked (matches
- 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
相关产品推荐
相关产品推荐

