引入redux.js:
https://cdn.bootcdn.net/ajax/libs/redux/4.2.0/redux.min.js
第一步:定义 reducer函数 作用:根据定义的数据状态修改之后返回新的状态
function reducer(state = {count: 0}, action) {
if (action.type === "ADD") {
state.count = state.count + 1;
return state
}
if (action.type === "REDUCE") {
state.count = state.count - 1
return state
}
return state
}
第二步:通过createStore方法,创建store 实例对象
const store = Redux.createStore(reducer);
console.log(store);
第三步:订阅实例store的subscribe方法
store.subscribe(() => {
document.getElementById("count").innerHTML = store.getState().count;
})
第四步:触发实例store 的 dispatch方法 提交Action
store.dispatch({
type: "REDUCE"
})
//第五步:通过实例store的getState方法获取最新的数据状态
store.getState().count;
完整代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Redux</title>
<script src="https://cdn.bootcdn.net/ajax/libs/redux/4.2.0/redux.min.js"></script>
</head>
<body>
<button id="reduction">-</button>
<button id="count">0</button>
<button id="add">+</button>
<script>
//第一步:定义 reducer函数 作用:根据定义的数据状态修改之后返回新的状态
function reducer(state = {count: 0}, action) {
if (action.type === "ADD") {
state.count = state.count + 1;
return state
}
if (action.type === "REDUCE") {
state.count = state.count - 1
return state
}
return state
}
//第二步:通过createStore方法,创建store 实例对象
const store = Redux.createStore(reducer);
console.log(store);
//第三步:订阅实例store的subscribe方法
store.subscribe(() => {
document.getElementById("count").innerHTML = store.getState().count;//第五步:通过实例store的getState方法获取最新的数据状态
})
onAdd()
//添加
function onAdd() {
let ele = document.getElementById("add");
ele.addEventListener('click', () => {
//第四步:触发实例store 的 dispatch方法 提交Action
store.dispatch({
type: "ADD"
})
})
}
onReduce();
//减少
function onReduce() {
let ele = document.getElementById("reduction");
ele.addEventListener('click', () => {
//第四步:触发实例store 的 dispatch方法 提交Action
store.dispatch({
type: "REDUCE"
})
})
}
</script>
</body>
</html>