关于redux的简易实现
- 最近在React的购物车项目中使用了redux,感觉蛮好用的,现在根据redux的使用来反向推测代码构成。
- 首先看看redux怎么使用的
redux的使用过程
- 首先定义reducer【reducer实际上可以理解为动态的state数据】
- 定义action,action就是触发reducer数据进行更新的方法
- 一般来说会有初始化的state数据
// state.js
// 初始化state数据
const state = {
// 定时器
num: 0
}
// 导出state数据
module.exports = state
- 定义reducer
// reducer.js
const initState = require("./state.js")
// 定义reducer
// reducer实际上就是动态的state数据
function num(state=initState.num, action){
case "ADD":
state = state + 1
return state
case "REDUCE":
state = state - 1
return state
default:
return state
}
// 导出reducer
module.exports = {
num
}
- 接下来就是重点,
combinaReducers
函数是用来收集reducer的,在这里我猜测是返回一个实例。 - 之后就是
createStore
,返回一个store,最后这两步就是redux的关键
function combinaReducers(reducers){
if(!(this instanceof combinaReducers)){
return new combinaReducers(reducers)
}
this.reducers = reducers
this.initState()
}
combinaReducers.prototype.initState = function(){
// 初始化state
this.state = {}
for(let p in this.reducers){
this.state[p] = this.reducers[p]()
}
}
// getState
combinaReducers.prototype.getState = function(){
return this.state
}
//dispatch
combinaReducers.prototype.dispatch = function(action){
// 要完全便利所有的reducers
for(let p in this.state){
this.state[p] = this.reducers[p](this.state[p], action)
}
}
// function createStore
// 接收reducers作为参数,然后但会一个store
function createStore(reducers){
// 返回一个store
return {
// 返回动态的state数据
getState: function(){
return reducers.getState()
},
// { type: "ADD", data }
dispatch: function(action){
reducers.dispatch(action)
}
}
}
const reducers = combinaReducers({ num })
const store = createStore(reducers)
console.log(store.getState())
store.dispatch({ type: "ADD" })
console.log(store.getState())
store.dispatch({ type: "ADD" })
console.log(store.getState())
store.dispatch({ type: "REDUCE" })
console.log(store.getState())
// 输出
{ num: 0 }
{ num: 1 }
{ num: 2 }
{ num: 1 }