Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { createStore } from "redux";
- const print = console.log;
- let nextTodoId = 0;
- // reduxのaction: todoを1つ追加する
- function addToDo(text) {
- return {
- type: "ADD_TODO",
- id: nextTodoId++,
- text: text
- };
- }
- // reduxのaction: todoの完了/未完了を変更する
- function toggleToDo(id) {
- return {
- type: "TOGGLE_TODO",
- id: id,
- };
- }
- // Reactの原則: 「変更は純粋な関数で書かれる」の通り
- // reducerは純粋な関数.
- // 第一引数のstateは, 現在のStoreの状態のこと
- // 第二引数にactionを受取り、そのactionのtypeによってstateに対する変更を行う
- // そして、新たなStore(変更されたstate)をreturnする
- function reducer(state, action) {
- switch(action.type) {
- case "ADD_TODO":
- return {
- // store.state.todoに受け取ったactionを追加する
- todo: state.todo.concat({
- id: action.id,
- text: action.text,
- completed: false,
- })
- };
- case "TOGGLE_TODO":
- return {
- todo: state.todo.map((t) => {
- if (t.id !== action.id) {
- return t;
- }
- return Object.assign({}, t, {completed: !t.completed});
- })
- };
- default:
- return state;
- }
- }
- const store = createStore(reducer, {todo: []});
- print("現在のStore(state)");
- print(store.getState());
- store.subscribe(() => {print(store.getState());});
- print("Add shopping");
- store.dispatch(addToDo("Go to shopping"));
- print("Add 銀行に行く");
- store.dispatch(addToDo("銀行に行く"));
- print("銀行に行くのをDone");
- store.dispatch(toggleToDo(1));
Add Comment
Please, Sign In to add comment