redux原理核心实现
createStore
创建 store 对象,包含 getState, dispatch, subscribe, replaceReducer
reducer
reducer 是一个计划函数,接收旧的 state 和 action,生成新的 state
action
action 是一个对象,必须包含 type 字段
dispatch
dispatch( action ) 触发 action,生成新的 state
subscribe
实现订阅功能,每次触发 dispatch 的时候,会执行订阅函数
combineReducers
多 reducer 合并成一个 reducer
replaceReducer
替换 reducer 函数
middleware
扩展 dispatch 函数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
function createStore(reducers){
//定义一个状态
let state = null;
//定义一个数组,存放一组在状态发生变换的时候处理的业务
let listeners = []
//发布订阅模式
function subscirbe(fn){
listeners.push(fn)
}
function dispatch(action) {
//reducer来源于reduce,一定是一个纯函数
state = reducers(state,action)
//出发listener里的函数
listeners.forEach(fn =>fn())
}
function getState(){
return state
}
//目的是初始化一次初始状态
dispatch({
type: "afasdf"
})
return {
dispatch,
getState,
subscirbe
}
}
const defaultState = {
count: 0
}
function reducers(state,action){
//初始化state
if(!state){
state = defaultState
}
switch(action.type){
case 'add':
//返回一个新的state
return {
count: state.count + 1
}
case 'minus':
return {
count: state.count - 1
}
default:
return state
}
}
const store = createStore(reducers)
store.subscirbe(()=>{
console.log(store.getState())
})
store.dispatch({type:'add'})
store.dispatch({type:'add'})
store.dispatch({type:'add'})
</script>
</body>
</html>
//{count: 1}
//{count: 2}
//{count: 3}