<!DOCTYPE html>
<html>
<head>
<title>Redux First Demo</title>
<script src="https://unpkg.com/redux@latest/dist/redux.min.js"></script>
</head>
<body>
<div>
<p>
Clicked: <span id="value">0</span> times
<button id="increment">+</button>
<button id="decrement">-</button>
</p>
</div>
<script>
// 定义一个函数Reducer,实现增加和减少
function counter(state, action) {
if(typeof state === "undefined") {
return 0
}
// 当定义的action的type
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
// 定义一个store,存储数据
var store = Redux.createStore(counter);
// 实现id为value的dom元素赋值
var valueEl = document.getElementById('value');
function render() {
// state为快照数据
valueEl.innerHTML = store.getState().toString()
}
render()
// 订阅状态变化
store.subscribe(render)
// 定义action
var actions = [
{ type: 'INCREMENT' },
{ type: 'DECREMENT' }
]
// 增加事件
document.getElementById('increment')
.addEventListener('click', function(){
// 分发action
store.dispatch(actions[0])
})
// 减少事件
document.getElementById('decrement')
.addEventListener('click', function(){
// 分发action
store.dispatch(actions[1])
});
</script>
</body>
</html>