忘了是哪里拷贝的Redux示例,睡前发博客手机看一看
<!DOCTYPE html>
<html>
<head>
<title>Redux basic example</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>
<button id="incrementIfOdd">Increment if odd</button>
<button id="incrementAsync">Increment async</button>
</p>
</div>
<script>
function reducer(state, action) { //[reducer]存放着action改动,对state进行操作 reducer(原state,action)
if (typeof state === 'undefined') {
return 0
}
switch (action.type) { //[action]
case 'INCREMENT':
return state + 1
case 'DECREMENT':
return state - 1
default:
return state
}
}
var store = Redux.createStore(reducer) //[store]用于储存state
var valueEl = document.getElementById('value') //
function render() {
valueEl.innerHTML = store.getState().toString() //获取store中的state,并转为字符串
}
render() //先渲染原state,在订阅subscribe后再渲染新state
store.subscribe(render)
document.getElementById('increment')
.addEventListener('click', function () {
store.dispatch({ type: 'INCREMENT' }) //dispatch调度reducer,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)
})
</script>
</body>
</html>