Redux作为状态管理不仅能在React使用、也能在node等其他地方使用
首先、先来看一段简单的代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<span id="txt"></span>
<button onclick="dispatch({type:'increment'})">increment</button>
<script>
const countState = {
count: 1
}
//渲染页面的函数
const render = () => {
let txt = document.getElementById('txt');
txt.innerHTML = countState.count;
}
// 点击事件的函数
const dispatch = (action) => {
//改变数据
changeState(action)
//渲染函数
render();
}
//只负责数据的修改
const changeState = (action) => {
switch (action.type) {
case "increment":
countState.count += 1;
break;
}
}
render(); //页面刚打开默认先执行一次
</script>
</body>
</html>
以上代码的changeState相当于redux中的reducer、只负责修改数据
其次想要把上面函数集中管理
*<button onclick="store.dispatch({type:'increment'})">increment</button>*
<script>
const countState = {
count: 1
}
const createStore = (reducer) => {
let state = null;
const listeners = [] //存储订阅的内容
const dispatch = (action) => {
state = reducer(action, state)
listeners.forEach((listener) => listener())
}
const getState = () => {
return state;
}
//订阅 当点击的时候给他个通知、他需要一个存储
const subscribe = (listener) => {
listeners.push(listener)
}
dispatch()
return {
dispatch,
getState,
subscribe
}
}
//只负责数据的修改(reducer)
const changeState = (action, state) => {
if (!action) {
return countState;
}
switch (action.type) {
case "increment":
return {
count: state.count + 1 //根据redux中state是只读的我们不能直接修改、所以返回一个新值
}
break;
}
}
const store = createStore(changeState);
//渲染函数
const render = () => {
let txt = document.getElementById('txt');
txt.innerHTML = store.getState().count;
}
render();
store.subscribe(render); //数据只要有改变就调用render
</script>
至此完成模拟的redux