在react的项目中,经常使用到redux来进行状态管理,项目中一般我选择使用react-redux!今天学习了一下自己实现一个简单的redux,来加深对react-redux的理解,代码如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<button onclick="store.dispatch({type: '-', num: 2})">-</button>
<span id="num">1</span>
<button onclick="store.dispatch({type: '+', num: 3})">+</button>
</body>
</html>
<script>
const dom = document.querySelector('#num');
const countState = {
count: 10
}
const changeState = (state,action) => {
if(!state) {
return countState
}
switch(action.type) {
case '-':
return {
...state,
count: state.count - action.num
}
break;
case '+':
return {
...state,
count: state.count + action.num
}
break;
default:
return state;
}
}
const createStore = (changeState) => {
let state = null;
const getState = () => state;
const listeners = [];
const subscribe = (listener) => listeners.push(listener);
const dispatch = (action) => {
state = changeState(state, action);
listeners.forEach(listener => listener());
}
// 默认值
dispatch({})
return {
getState,
dispatch,
subscribe,
}
}
//创建store统一管理状态
const store = createStore(changeState);
// 渲染函数
const render = (state)=> {
dom.innerHTML = store.getState().count;
}
// 初次渲染
render(countState);
// 每次更新页面
store.subscribe(render);
</script>