(一)Redux:在计数器中(Counter)的使用

(一)Redux:在计数器中(Counter)的使用

摘要:Redux为了解决各种状态的在代码中离散

store接收(dispatch)一个事件(type),选择对应的响应(Action),触发对视图的回调(注:必须订阅subscribe,才有回调)

请始终牢记!


以Redux实现一个计数器(Counter)

视图

html组件依次是增加,减少,偶数加,异步加

<p>
Clicked: <span id="value">0</span> times
<button id="increment">+</button>
<button id="decrement">-</button>
<button id="incrementIfOdd">Increment if odd</button>
<button id="incrementAsync">Increment async</button>
</p>

动作(dispatch)

JS代码中为按钮增加了监听



      document.getElementById('increment')
        .addEventListener('click', function () {
        //告诉
          store.dispatch({ type: 'INCREMENT' })
        })

      document.getElementById('decrement')
        .addEventListener('click', function () {
          store.dispatch({ type: 'DECREMENT' })
        })

      document.getElementById('incrementIfOdd')
        .addEventListener('click', function () {
          if (store.getState() % 2 !== 0) {
            store.dispatch({ type: 'INCREMENT' })
          }
        })

      document.getElementById('incrementAsync')
        .addEventListener('click', function () {
          setTimeout(function () {
            store.dispatch({ type: 'INCREMENT' })
          }, 1000)
        })


目前有四个Button和一个P标签,

分别实现了

告诉(dispatch)某个对象(store)我要做某件事情

这件事情以状态分类(type)

Store(存储当前状态,拥有对所有状态的解决方案)

store

解决方案:store接收(dispatch)一个事件(type),选择对应的响应(Action),触发对视图的回调(注:必须订阅subscribe,才有回调)

        //一个事件(type),选择对应的响应(Action)
      function counter(state, action) {
        if (typeof state === 'undefined') {
          return 0
        }

        switch (action.type) {
          case 'INCREMENT':
            return state + 1
          case 'DECREMENT':
            return state - 1
          default:
            return state
        }
      }


      var store = Redux.createStore(counter)



      var valueEl = document.getElementById('value')

      //回调
      function render() {
        valueEl.innerHTML = store.getState().toString()
      }

      //视图的初始化
      render()

      //订阅
      store.subscribe(render)

在Redux中,我们将事件的生命周期抽离出来

在实际的工程运用中,将离散的事件和状态统一交给redux管理

至此,我们知道Redux是怎样发挥作用的

更多信息,请查看我的Github

https://github.com/RoJoHub/Redux-Tutorial

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值