Learn how to create a React todo list application using the reducers we wrote before.
/** * A reducer for a single TODO * @param state * @param action * @returns {*}*/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 ; }};/** * The reducer for the todos * @param state * @param action * @returns {*}*/Const Todos= (state = [], action) = = { Switch(action.type) { Case' Add_todo ': return[... state, Todo (undefined, action)]; Case' Toggle_todo ': returnState.map (t =Todo (T, action)); default: returnState ; }};/** * Reducer for the visibilityfilter * @param state * @param action * @returns {*}*/Const Visibilityfilter= (state = ' show_all '), Action)= { Switch(action.type) { Case' Set_visibility_filter ': returnAction.filter; default: returnState ; }};/** * combinereducers:used for merge reducers Togethger * Createstore:create a redux store*/Const {combinereducers, createstore}=Redux;const Todoapp=combinereducers ({todos, visibilityfilter}); Const store=CreateStore (Todoapp);/** * For generate TODO ' s ID * @type {number}*/Let nexttodoid= 0;/** * React related*/const {Component}=React;class Todoapp extends Component {render () {return ( <div> <input ref={(node)={ This. Input =node}}/> <button onclick={ ()={ //After clicking the button, dispatch a add TODO actionStore.dispatch ({type:' Add_todo ', Id:nexttodoid++, Text: This. Input.value}) This. Input.value = ""; } }>ADD Todo</button> <ul>//Loop thought the todo list{ This. Props.todos.map (TODO) = { return<li key={todo.id}>{todo.text}</li> } )} </ul> </div> ); }}const Render= () + ={Reactdom.render (<todoapp todos={store.getstate (). Todos}/>, document.getElementById (' root ' ) );};//every time, store updated, also fire the render () functionStore.subscribe (render); render ();
<!DOCTYPE HTML><HTML><Head> <Scriptsrc= "Https://cdnjs.cloudflare.com/ajax/libs/redux/3.0.4/redux.js"></Script> <Scriptsrc= "Https://fb.me/react-0.14.0.js"></Script> <Scriptsrc= "Https://fb.me/react-dom-0.14.0.js"></Script> <title>JS Bin</title></Head><Body> <DivID= "root"></Div></Body></HTML>
[Redux] React Todo List Example (Adding a Todo)