[Redux] Normalizing the State Shape

We will learn how to normalize the state shape to ensure data consistency that is important in real-world applications.

 

We currently represent the todos in the state free as an array of todo object. However, in the real app, we probably have more than a single array and then todos with the same IDs in different arrays might get out of sync.

复制代码
const byIds = (state = {}, action) => {
  switch (action.type) {
    case 'ADD_TODO':
    case 'TOGGLE_TODO':
      return {
        ...state,
        [action.id]: todo(state[action.id], action),
      };
    default:
      return state;
  }
};
复制代码

 

For using object spread, we need to include plugins:

// .baberc

{
  "presets": ["es2015", "react"],
  "plugins": ["transform-object-rest-spread"]
}

 

Anytime the ByID reducer receives an action, it's going to return the copy of its mapping between the IDs and the actual todos with updated todo for the current action. I will let another reducer that keeps track of all the added IDs.

const allIds = (state = [], action) => {
  switch(action.type){
    case 'ADD_TODO':
      return [...state, action.id];
    default:
      return state;
  }
};

the only action I care about is a todo because if a new todo is added, I want to return a new array of IDs with that ID as the last item. For any other actions, I just need to return the current state.

 

Finally, I still need to export the single reducer from the todos file, so I'm going to use combined reducers again to combine the ByID and the AllIDs reducers.

const todos = combineReducers({
  allIds,
  byIds
});

export default todos;

 

Now that we have changed the state shape in reducers, we also need to update the selectors that rely on it. The state object then get visible todos is now going to contain ByID and AllIDs fields, because it corresponds to the state of the combined reducer.

复制代码
const getAllTodos = (state) => {
  return state.allIds.map( (id) => {
    return state.byIds[id];
  })
};

export const getVisibleTodos = (state, filter) => {
  const allTodos = getAllTodos(state);
  console.log(allTodos);
  switch (filter) {
    case 'all':
      return allTodos;
    case 'completed':
      return allTodos.filter(t => t.completed);
    case 'active':
      return allTodos.filter(t => !t.completed);
    default:
      throw new Error(`Unknown filter: ${filter}.`);
  }
};
复制代码

 

My todos file has grown quite a bit so it's a good time to extract the todo reducer that manages just when you go todo into a separate file of its own. I created a file called todo in the same folder and I will paste my implementation right there so that I can import it from the todos file.

复制代码
// reducers/todo.js
const todo = (state, action) => { switch (action.type) { case 'ADD_TODO': return { id: action.id, text: action.text, completed: false, }; case 'TOGGLE_TODO': if (state.id !== action.id) { return state; } return { ...state, completed: !state.completed, }; default: return state; } };
复制代码

 

------------------

复制代码
//todos.js

import { combineReducers } from 'redux';
import  todo  from './todo';

const byIds = (state = {}, action) => {
  switch (action.type) {
    case 'ADD_TODO':
    case 'TOGGLE_TODO':
      return {
        ...state,
        [action.id]: todo(state[action.id], action),
      };
    default:
      return state;
  }
};

const allIds = (state = [], action) => {
  switch(action.type){
    case 'ADD_TODO':
      return [...state, action.id];
    default:
      return state;
  }
};

const todos = combineReducers({
  allIds,
  byIds
});

export default todos;

const getAllTodos = (state) => {
  return state.allIds.map( (id) => {
    return state.byIds[id];
  })
};

export const getVisibleTodos = (state, filter) => {
  const allTodos = getAllTodos(state);
  console.log(allTodos);
  switch (filter) {
    case 'all':
      return allTodos;
    case 'completed':
      return allTodos.filter(t => t.completed);
    case 'active':
      return allTodos.filter(t => !t.completed);
    default:
      throw new Error(`Unknown filter: ${filter}.`);
  }
};
复制代码

 

复制代码
//todo.js
const todo = (state, action) => {
    switch (action.type) {
        case 'ADD_TODO':
            return {
                id: action.id,
                text: action.text,
                completed: false,
            };
        case 'TOGGLE_TODO':
            if (state.id !== action.id) {
                return state;
            }
            return {
                ...state,
                completed: !state.completed,
            };
        default:
            return state;
    }
};

export default todo;
复制代码

 

posted @   Zhentiw  阅读(298)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2015-06-07 [D3 + AngularJS] 15. Create a D3 Chart as an Angular Directive
点击右上角即可分享
微信分享提示