04.redux整体感知

如果比较着急想了解一些原理可以先看这篇文章

https://segmentfault.com/a/1190000015754271

  1. // reducer
  2. const weight = (state = 160, action) => {
  3. switch (action.type) {
  4. case 'eat':
  5. return state + 10
  6. case 'hungry':
  7. return state - 10
  8. default:
  9. return 160
  10. }
  11. }
  12. const store = createStore(weight)
  13. console.log(store.getState())
  14. store.dispatch({ type: 'eat' })
  15. console.log('我吃了一些事物')
  16. console.log(store.getState())
  17. console.log('我饿了好几天')
  18. store.dispatch({ type: 'hungry' })
  19. console.log(store.getState())
  20. console.log('我又饿了好几天')
  21. store.dispatch({ type: 'hungry' })
  22. console.log(store.getState())

reducer 里面使用switch语句根据传入的类型,输出新的状态

把reducer 传入 createStore(weight)

通过 dispatch 传入不同的类型,改变状态state。

  1. store.dispatch({ type: 'hungry' })

通过 store.getState() 获取当前的状态