//导入redux不能用ES6方式 import export
//使用commonjs方式
const redux=require('redux');
//初始化数据,它是放到reducer中使用
const initialState={
counter:0
}
//创建reducer纯函数 第一个参数是state,可以用初始化值作为默认值,有了reducer创建store
function reducer(state=initialState,action){
switch(action.type){
case "INCREMENT":
return {...state,counter:state.counter+1}
case "DECREMENT":
return {...state,counter:state.counter-1}
case "ADD_NUM":
return {...state,counter:state.counter+action.num}
case "SUB_NUM":
return {...state,counter:state.counter-action.num}
default:
return state;
}
}
//创建store:store在创建的时候需要传入一个reducer
const store=redux.createStore(reducer)
//订阅监听counter的修改
store.subscribe(()=>{
console.log("counter:",store.getState().counter)
})
//创建一个个actions
const action1={type:'INCREMENT'};
const action2={type:'DECREMENT'};
const action3={type:'ADD_NUM',num:5};
const action4={type:'SUB_NUM',num:12};
//派发action
store.dispatch(action1);
store.dispatch(action2);
store.dispatch(action3);
store.dispatch(action4);
//一旦开始执行派发dispatch,其内部就会去执行reducer函数,也就是通过store一旦派发了action,
//内部就会执行创建的reducer函数,执行reducer时候,会传入前一个state作为参数,
//第一次执行时候没有state值 可以使用默认值
//第二个参数就是派发的action
//如何验证state确实作了修改呢?
//订阅store的修改
store.subscribe(()=>{
console.log("state发生了改变")
})
react——简化版redux:在一个文件中使用redux
最新推荐文章于 2023-06-30 17:20:07 发布