react的状态管理,类似于vue的vuex;
不同点是:redux可以不依赖react使用,REACT没有redux也可以使用,vuex必须依赖vue使用
公共的共享数据
redux渲染流程
reducer为更改store里数据的东西,通过reducer去和state交互
流程为
:
store.getState();//获取store中的共享数据
store.subscribe(函数)//redux的发布订阅功能,store改变触发某个函数(利用这个修改组件内state的值)
store.dispatch(action)//action应该是个对象,用来派发修改store中的值
想使用redux状态管理的话,要先创建store
import {createStore} from "redux"
import 自己写的reducer from 路径
const store=createStore(reducer,增强器,中间件)
//如果只有两个参数const store=createStore(reducer,中间件||中间件)
//如果想使用中间件的话,要导入middleWare从redux中
export default store
reducer的思路:
reducer是会拷贝一份原有的数据,然后去匹配传过来的action的类型;
判断这个类型action,然后将复制的新的state修改成需要的state;
将这个state返回去替换原本的state;
用一个变量接收返回之后的action(即新的state);
用store.dispatch(action值)来对store值进行修改
写法例:
import * as Types from "../actionType"
const initState = {
value: 789
}
export default (state = initState, action) => {
const newState = JSON.parse(JSON.stringify(state));
if (action.type == Types.HANDLE_ADD) {
console.log(newState.value ,action.value)
newState.value = newState.value + action.value
return newState
}
return state
}