//发布订阅模式
//也称作观察者模式,定义了对象间的一对多的依赖关系,
//当一个对象的状态发 生改变时,所有依赖于它的对象都将得到通知
//createStor dispatch subscribe
class MyRedux{
constructor(){
this.container = []
}
getState(){
return this.state
}
subscribe(fn){//订阅函数,订阅一些更新逻辑
this.container.push(fn)
}
notify(value){//发布订阅
this.container.forEach((fnItem)=>{
fnItem(value)
})
}
dispatch(action){
//调用reducer传入上次的state值,它的返回值覆盖上次的state
this.state = this.reducer(this.state,action)
//this.state如果发生了改变,那么就发布 immer
this.notify(this.state)
}
static instanceStor
static createStor(reducer){
if(MyRedux.instanceStor){
return MyRedux.instanceStor
}else{
//实例化仓库
let store = new MyRedux()
//初次是state是undefined,reducer返回赋值给store
store.state = reducer(undefined,{})
//挂载reducer
store.reducer = reducer
//返回
return MyRedux.instanceStor = store
}
}
}
//声明初始值
const defaultState = {
username:'zhangsan'
}
//创建store仓库并传入reducer,store就是创建的仓库实例
let stor = MyRedux.createStor((state=defaultState,action)=>{
console.log(state,action);
switch(action.type){
case 'changename':
return {...state,username:action.value}
default:
return {...state}
}
})
//订阅仓库
stor.subscribe((value)=>{
console.log(value,'仓库值更新后同步刷新组件视图')
})
console.log(stor.getState().username)
//提交action
stor.dispatch({
type:'changename',
value:'lisi'
})
console.log(stor.getState().username)
redux模拟实现
最新推荐文章于 2024-08-10 16:15:00 发布