React+Redux排序后内容不重渲染问题的排查与解决求助
Fixing Redux Sorting Not Triggering Component Re-Render
Hey there! I see exactly where the issue is here—your reducer is mutating the original state instead of returning a new immutable state, which is why Redux isn't detecting a change and your component isn't re-rendering when you sort. Let's fix this step by step.
The Root Problems
Array.sort()mutates the original array: When you callgroup.tasks.sort(...), you're directly modifying thetasksarray in the existing state. Redux compares references, so since the array reference hasn't changed, it thinks nothing has updated.- You're reusing the original
groupsarray reference: The linegroups = state.groupsjust points to the original state's groups array, and yourmapresult isn't being saved—so you end up returning the exact same groups array reference to Redux.
Fixed Reducer Code for SORT_BY Case
case SORT_BY: // Create a copy of the entire groups array to avoid mutating the original const updatedGroups = state.groups.map((group, groupId) => { if (groupId === action.payload.group_id) { // Create a copy of the tasks array BEFORE sorting (since sort is in-place) const sortedTasks = [...group.tasks].sort((a, b) => { return a.title.localeCompare(b.title); // More reliable for string sorting }); // Return a new Group instance with the sorted tasks return new Group(group.title, sortedTasks); } // Return the original group for unmodified entries return group; }); // Return a new state object with the updated groups array return { ...state, groups: updatedGroups };
Key Changes Explained
- Copied the groups array: Using
state.groups.map(...)creates a new array instead of reusing the original reference. - Copied tasks before sorting:
[...group.tasks]spreads the existing tasks into a new array, so when we callsort()we're modifying this new array instead of the original state's tasks. - Returned a new state object:
{ ...state, groups: updatedGroups }ensures we're not mutating the original state object—we're creating a new one with the updated groups. - Used
localeComparefor string sorting: This handles edge cases like special characters and different language sets better than a simplea.title > b.titlecomparison.
Reducer Best Practices to Remember
- Never mutate state directly: Always return new objects/arrays instead of modifying existing ones.
- Use immutable array methods: Prefer
map,filter,concat, or spread syntax ([...arr]) over in-place methods likesort,push,splice. - Update state immutably: For objects, use spread syntax (
{ ...obj, key: newValue }) orObject.assignto create new objects instead of modifying properties directly.
Once you update your reducer with this code, clicking the sort button will return a new immutable state, Redux will detect the change, and your component will re-render with the sorted tasks immediately.
内容的提问来源于stack exchange,提问作者Yuriy Lesyo
相关产品推荐
相关产品推荐

