什么是redux
redux是一种状态管理工具,类似于vue中的vuex
redux的三大原则
1: 单一数据源
2: state是只读的,修改state唯一方法就是触发action
3: 使用纯函数 reducer来修改state,返回一个新的state给store
redux的工作流程
const redux = require('redux')
// redux三大块 store action reducer
const initState = {
count: 0,
}
// 1、action用来修改store
const action1 = { type: 'INCREMENT' }
const action2 = { type: 'DECREMENT' }
const action3 = { type: 'ADDNUM', num: 10 }
const action4 = { type: 'REDUCENUM', num: 20 }
// 2、reducer是连接store和action,返回新的state给store
const reducer = (state = initState,action) => {
switch (action.type) {
case "INCREMENT": return {...state,count: state.count + 1}
case "DECREMENT": return {...state,count: state.count - 1}
case "ADDNUM": return {...state,count: state.count + action.num }
case "REDUCENUM": return {...state,count: state.count - action.num }
}
}
// 3、store保存状态,创建一个对象即可
const store = redux.createStore(reducer);
// 5: 在派发之前监听store的变化
store.subscribe(() => {
console.log(`count:${store.getState().count}`);
})
// 4、派发action
store.dispatch(action1)
store.dispatch(action2)
store.dispatch(action3)
store.dispatch(action4)
展示效果如下
![image.png](https://i-blog.csdnimg.cn/blog_migrate/217f40be87117d73e26af3681df16244.png)