为什么要有Redux
- 防止对象任意被修改
- 明确修改对象的一些行为,方便后期维护,明确是哪些用户行为修改了对象
开发一个redux应用的步骤就是
1.定义action和与之对应的reducer
2.监听store的变化,提供回调函数
3.dispatch一个action
第一步
创建一个状态管理的仓库
const createStore=function(initState,reducer){
let state=initState;
let listenerList=[];
let getState=function(){
return state;
}
let subscribe=function(listener){
listenerList.push(listener);
}
let dispatch=function(action){
state=reducer(state,action);
listenerList.forEach((listener)=>{
listener();
})
}
return {
subscribe,
dispatch,
getState
}
}
const initState={
name:'www'
}
const action={
type:'UPDATE_NAME',
value:'xxx'
}
const reducer=function(state,action){
switch (action.type){
case 'UPDATE_NAME':
return {
...state,
name:action.value
}
default:return state
}
}
使用
const store=createStore(initState,reducer);
//订阅store
store.subscribe(()=>{
let state=store.getState();
alert(state);//弹出我是谁
})
//触发动作
store.dispatch({
type:'UPDATE_NAME',
value:'我是谁'
})