50行代码 实现Redux 核心功能
Redux 帮助你管理“全局”状态 - 那些应用程序的许多部分都需要的状态
redux的核心就是对数据状态进行管理,创建一个数据仓库

Redux顺序分四大步:

  1. 初始化
  2. 订阅
  3. 发布
  4. 执行匹配和更新

 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Redux</title>
	</head>
	<body>
		<button id="addto">加1</button>
	</body>

	<script>
		// 创建全局变量
		window.Redux = {};

		function createStore(reducer) {
			// state 是存储在store中的数据
			let state;
			let listeners = [];
			// 获取最新的state仓库内容
			function getState() {
				return state
			};
			// 订阅,发布 
			function subscribe(callback) {
				listeners.push(callback)
			};

			// reducer 修改state,接收参数action
			function dispatch(action) {
				// 更新仓库
				state = reducer(state, action);
				// 循环执行订阅过的subscribe函数回调
				for (let i = 0; i < listeners.length; i++) {
					let listener = listeners[i]
					listener()
				}
			};

			// 在store初始化的时候需要执行一次reducer
			state = reducer(state, {
				type: '@@init/redux.x.x.x'
			});

			let store = {
				getState,
				subscribe,
				dispatch
			};
			return store;
		};
		Redux.createStore = createStore;

		const initState = {
			milk: 0
		};
		
		// 执行 action 对应的type更新 state仓库
		function reducer(state = initState, action) {
			switch (action.type) {
				case 'PUTMILK':
					return {
						...state, milk: state.milk + action.count
					}
				case 'TAKE_MILK':
					return {
						...state, milk: state.milk - action.count
					}
				case '@@init/redux.x.x.x':
					return { ...state }
				default:
					return state
			}
		};
		
		
		
		// redux 的使用
		// 初始化
		let store = createStore(reducer);
		// 订阅,只要state发生改变 就会通知订阅者
		store.subscribe(() => console.log('仓库更新了',store.getState()));
		// 发布-执行
		store.dispatch({
			type: 'PUTMILK',
			count: 1
		});

		let dom = document.getElementById("addto");
		dom.onclick = () => {
			store.dispatch({
				type: 'PUTMILK',
				count: 1
			});
			console.log(store.getState())
		};
	</script>
</html>