Guest User

Untitled

a guest
Oct 17th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. import { createStore } from "redux";
  2.  
  3. const print = console.log;
  4.  
  5. let nextTodoId = 0;
  6.  
  7. // reduxのaction: todoを1つ追加する
  8. function addToDo(text) {
  9. return {
  10. type: "ADD_TODO",
  11. id: nextTodoId++,
  12. text: text
  13. };
  14. }
  15.  
  16. // reduxのaction: todoの完了/未完了を変更する
  17. function toggleToDo(id) {
  18. return {
  19. type: "TOGGLE_TODO",
  20. id: id,
  21. };
  22. }
  23.  
  24. // Reactの原則: 「変更は純粋な関数で書かれる」の通り
  25. // reducerは純粋な関数.
  26. // 第一引数のstateは, 現在のStoreの状態のこと
  27. // 第二引数にactionを受取り、そのactionのtypeによってstateに対する変更を行う
  28. // そして、新たなStore(変更されたstate)をreturnする
  29. function reducer(state, action) {
  30. switch(action.type) {
  31. case "ADD_TODO":
  32. return {
  33. // store.state.todoに受け取ったactionを追加する
  34. todo: state.todo.concat({
  35. id: action.id,
  36. text: action.text,
  37. completed: false,
  38. })
  39. };
  40. case "TOGGLE_TODO":
  41. return {
  42. todo: state.todo.map((t) => {
  43. if (t.id !== action.id) {
  44. return t;
  45. }
  46. return Object.assign({}, t, {completed: !t.completed});
  47. })
  48. };
  49. default:
  50. return state;
  51. }
  52. }
  53.  
  54. const store = createStore(reducer, {todo: []});
  55. print("現在のStore(state)");
  56. print(store.getState());
  57. store.subscribe(() => {print(store.getState());});
  58.  
  59. print("Add shopping");
  60. store.dispatch(addToDo("Go to shopping"));
  61.  
  62. print("Add 銀行に行く");
  63. store.dispatch(addToDo("銀行に行く"));
  64.  
  65. print("銀行に行くのをDone");
  66. store.dispatch(toggleToDo(1));
Add Comment
Please, Sign In to add comment