redux
2019-03-03 本文已影响0人
是嘻嘻呀
redux原理
![](https://img.haomeiwen.com/i10574882/1d9d8d759d8c7b6c.png)
reducer(state,action):当前的state和action,返回新的state;
store:存放state的对象;
state:唯一的state值,通过store.getState()获取;
Action:普通对象,用来表示即将改变state。action 内必须使用一个字符串类型的 type 字段来表示将要执行的动作;
Dispatch(action):往store发送action;
Action Create:创建action的函数
实现一个store;
const createStore = (reducer) =>{ //返回dispath、getstate、subscribe
let state;
const list = [];
const dispath = (action) => {//触发action
state = reducer(state,action);
list.forEach((cb)=>{
cb()
});
}
const getState = () => {//获取state
return state
}
const subscribe = (callback) => {//订阅回调函数
list.push(callback)
}
return {
dispath,
getState,
subscribe
}
}
const reducer = (state,action)=>{
if (state === undefined) {
return 0
}
switch (action.type) {
case 'DECREASEMENT':
return state+1
break;
case 'INCREASEMENT':
return state-1
break;
}
}
const store = createStore(reducer)
store.subscribe(()=>{
console.log('fn1-----:'+store.getState())
})
store.subscribe(()=>{
console.log('fn2-----:'+store.getState())
})
store.dispath({
type:'DECREASEMENT'
})
store.dispath({
type:'INCREASEMENT'
})
store.dispath({
type:'INCREASEMENT'
})