We'll learn how to encapsulate the knowledge on the state of shape in the reducer files and so that the components don ' t ha ve to rely on it.
In current visibletodolist.js:
Import {Connect} from ' React-redux '; import {withrouter} from' React-router '; import {Toggletodo} from‘.. /actions '; import ToDoList from'./todolist '; Const Getvisibletodos= (Todos, filter) = = { Switch(filter) { Case' All ': returnTodos; Case' Completed ': returnTodos.filter (t =t.completed); Case' Active ': returnTodos.filter (t =!)t.completed); default: Throw NewError (' Unknown filter: ${filter}. '); }};const Mapstatetoprops= (state, {params}) = =({todos:getvisibletodos (state.todos, Params.filter|| ' All ',}); const visibletodolist=withrouter (Connect (mapstatetoprops, {Ontodoclick:toggletodo}) (todolist)); ExportdefaultVisibletodolist;
Currently, the Getvisibletodos (State.todos), depends on state ' s structure.
Move Getvisibletodos to reducer file:
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) {returnState ; } return{... state, completed:!state.completed,}; default: returnState ; }};const Todos= (state =[{ID:0, Text:"OK", Completed:false}], action)= { Switch(action.type) { Case' Add_todo ': return[... state, Todo (undefined, action),]; Case' Toggle_todo ': returnState.map (t =Todo (T, action)); default: returnState ; }};exportdefaulttodos;export const Getvisibletodos = (state, filter) = = { Switch(filter) { Case' All ': returnState ; Case' Completed ': returnState.filter (t =t.completed); Case' Active ': returnState.filter (t =!)t.completed); default: Throw NewError (' Unknown filter: ${filter}. '); }};
Then on the rootreducer, we manage the state:
Import {combinereducers} from ' redux '* as Fromtodos from './todos '= combinereducers ({ c4/>defaultgetvisibletodos= (state, filter) = fromtodos.getvisibletodos (State.todos, filter);
Use it in Visibletodolist.js:
Import {Connect} from ' React-redux '; import {Toggletodo} from‘.. /actions '; import ToDoList from'./todolist '; import {withrouter} from' React-router '; Import {Getvisibletodos} from'. /reducers '; Const Mapstatetoprops= (state, {params}) = = { return{todos: getvisibletodos(State, Params.filter|| ' All '),//if filter is " then change to ' all ' };}; Const Visibletodolist=withrouter (Connect (mapstatetoprops, {Ontodoclick:toggletodo}) (todolist)); ExportdefaultVisibletodolist;
[Redux] Colocating selectors with Reducers