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;

[Redux] Normalizing the State Shape的更多相关文章

  1. 关于props和state以及redux中的state

    React的数据模型分为共有数据和私有数据,共有数据可以在组件间进行传递,私有数据为当前组件私有.共有数据在React中使用props对象来调用,它包含标签所有的属性名称和属性值,props对象有三个 ...

  2. [Redux] Persisting the State to the Local Storage

    We will learn how to use store.subscribe() to efficiently persist some of the app’s state to localSt ...

  3. [Functional Programming ADT] Create a Redux Store for Use with a State ADT Based Reducer

    With a well defined demarcation point between Redux and our State ADT based model, hooking up to a R ...

  4. 前端(十一):props、state及redux关系梳理

    所谓状态机,是一种抽象的数据模型,是“事物发展的趋势”,其原理是事件驱动.广泛地讲,世界万物都是状态机. 一.状态机是一种抽象的数据模型 在react中,props和state都可以用来传递数据.这里 ...

  5. Redux的State不应该全部放在Store里

    使用了redux管理应用的状态,应用的状态不应该全部放在Store里面. 前端状态主要有一下两种: 1. Domain data 2. UI State 1. Domain data 来自于服务端对领 ...

  6. [Redux] Colocating Selectors with Reducers

    We will learn how to encapsulate the knowledge about the state shape in the reducer files, so that t ...

  7. 详解 Node + Redux + MongoDB 实现 Todolist

    前言 为什么要使用 Redux? 组件化的开发思想解放了繁琐低效的 DOM 操作,以 React 来说,一切皆为状态,通过状态可以控制视图的变化,然后随着应用项目的规模的不断扩大和应用功能的不断丰富, ...

  8. redux的源码解析

    一. redux出现的动机 1. Javascript 需要管理比任何时候都要多的state2. state 在什么时候,由于什么原因,如何变化已然不受控制.3. 来自前端开发领域的新需求4. 我们总 ...

  9. [Redux] Important things in Redux

    Root Smart component can be overloaded, divide 'smart' component wisely & using Provider. Proble ...

随机推荐

  1. 模拟google分页效果

    /// </summary> /// <param name="total">总记录数</param> /// <param name=& ...

  2. ubuntu修改grub2

    转自修改系统启动项 grub2配置的方法 ubuntu 在早期的Ubuntu中,使用Grub作为系统的启动引导程序,想修改系统启动项非常简单,只要用gedit打开系统菜单设定文件( sudo gedi ...

  3. PYTHON--CLASS

    class Robot: population = 0 def __init__(self, name): self.name = name print("(Initializing {0} ...

  4. Centos6.5 安装Vim7.4

    系统本身会带Vim7.2都版本,其实也够用,强迫症患者可以按以下操作升级成Vim7.4: (1)切换到root权限 (2)卸载 rpm -qa | grep vim yum remove vim vi ...

  5. SharePoint用户控件编写的简单介绍

    转:http://www.it165.net/design/html/201204/1131.html 我们开发中,通常需要写各种各样的部件来实现我们的展示或者功能,下面就介绍下刚刚接触的QuickP ...

  6. jquery方法详解--bind(type, [data], fn)

    转自:http://www.zhufengpeixun.cn/jquery/bind_type_data_fn.html bind(type, [data], fn)  返回值::jQuery 概述 ...

  7. Tag file directory /struts-tags does not start with "/WEB-INF/tags"

    使用自定义标签,记得引用路径 <%@taglib prefix="s" uri="/struts-tags" %>

  8. Jquery扩展- 倒计时

    Source Code (function($) { $.fn.countdown = function(options) { // default options var defaults = { ...

  9. HTML5 Canvas核心技术—图形、动画与游戏开发.pdf2

    事件处理: HTML5应用程序是以事件来驱动的,可以在canvas中增加一个事件监听器,当事件发生时,浏览器就会调用这个监听器 //方法一canvas.onmousedown=function(e){ ...

  10. 在bootloader及IAP中使用zlib解压缩

    原有的bootloader方案是在片内FLASH上面分成3块,bootloader区占一小块,然后剩下区域平分成两块,一块是运行区,一块是新固件临时存储区. 好在现在FLASH在系统成本中占的比例越来 ...