Advertisement
xapu

Untitled

Nov 5th, 2017
415
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.72 KB | None | 0 0
  1. import React from 'react'
  2. import ReactDOM from 'react-dom'
  3. import './index.css'
  4. import App from './App'
  5. import registerServiceWorker from './registerServiceWorker'
  6.  
  7. import { createStore } from 'redux'
  8.  
  9. let generatorReducer = (store, action) => {
  10. switch (action.type) {
  11. case 'ADD_COUNTER':
  12. return [...store, { index: store.length, value: 0 }]
  13. case 'REMOVE_COUNTER':
  14. return [...store.slice(0, store.length - 1)]
  15. case 'INCREMENT':
  16. return [
  17. ...store.slice(0, action.index),
  18. Object.assign({}, store[action.index], {
  19. value: store[action.index].value + 1
  20. }),
  21. ...store.slice(action.index + 1)
  22. ]
  23. case 'DECREMENT':
  24. return [
  25. ...store.slice(0, action.index),
  26. Object.assign({}, store[action.index], {
  27. value: store[action.index].value - 1
  28. }),
  29. ...store.slice(action.index + 1)
  30. ]
  31. case 'CLEAR':
  32. return [
  33. ...store.slice(0, action.index),
  34. Object.assign({}, store[action.index], { value: 0 }),
  35. ...store.slice(action.index + 1)
  36. ]
  37. default:
  38. return store
  39. }
  40. }
  41.  
  42. let store = createStore(generatorReducer, [{ index: 0, value: 0 }])
  43. let Counter = () => {
  44. return (
  45. <h1 className='App'>
  46.  
  47. {store.getState().map(elem => {
  48. return (
  49. <div key={elem.index}>
  50. <h1>{elem.value}</h1>
  51. <button
  52. onClick={() => {
  53. store.dispatch({
  54. type: 'INCREMENT',
  55. index: elem.index
  56. })
  57. }}
  58. >
  59. INCREMENT
  60. </button>
  61. <button
  62. onClick={() => {
  63. store.dispatch({
  64. type: 'DECREMENT',
  65. index: elem.index
  66. })
  67. }}
  68. >
  69. DECREMENT
  70. </button>
  71. <button
  72. onClick={() => {
  73. store.dispatch({
  74. type: 'CLEAR',
  75. index: elem.index
  76. })
  77. }}
  78. >
  79. CLEAR
  80. </button>
  81. </div>
  82. )
  83. })}
  84. <button
  85. onClick={() => {
  86. store.dispatch({
  87. type: 'ADD_COUNTER'
  88. })
  89. }}
  90. >
  91. ADD
  92. </button>
  93. <button
  94. onClick={() => {
  95. store.dispatch({
  96. type: 'REMOVE_COUNTER'
  97. })
  98. }}
  99. >
  100. REMOVE
  101. </button>
  102. </h1>
  103. )
  104. }
  105. store.subscribe(() => {
  106. ReactDOM.render(<Counter />, document.getElementById('root'))
  107. })
  108. ReactDOM.render(<Counter />, document.getElementById('root'))
  109. registerServiceWorker()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement