(一)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接收(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