Flux思想:把所有的组件使用到状态[数据]都保存同一个地方,进行统一的管理,修改入口统一,是一种数据共享的思想。Vuex和Redux都是Flux具体体现.
react中使用Redux需要安装:npm i react-redux
对比 | Vuex | Redux |
初始化值 | state | state |
读取 | this.$store.state.xxx | store.getState() |
定义修改方法 | mutations | reducer |
修改/调用 | this.$store.commit() | store.dispatch() |
1、导入createStore
import { createStore } from "redux";
2、初始化值
const initState = { num: 1, skills: ["vue", "react", "angular"], count: 10 };
3、定义修改方法:
参数1:初始值
参数2:操作方法的名称,action一般作为对象格式,type操作方法
参数格式: action = { type: "doAdd" };
注意:每次都要把state return
4、创建store管理reducer
const store = createStore(reducer);
5、修改、调用
store.dispatch({ type: "doAdd" });
console.log(store.getState().num);
//导入createStore
import { createStore } from "redux";
//1、初始化值
const initState = { num: 1, skills: ["vue", "react", "angular"], count: 10 };
//2、定义修改方法:
const reducer = (state = initState, action) => {
switch (action.type) {
case "doAdd":
return { ...state, num: state.num + 1 };
case "appendSkill":
return { ...state, skills: [...state.skills, action.skill] };
case "addCount":
return { ...state, count: state.count + 10 };
default:
return state
}
};
//3、创建store管理reducer
const store = createStore(reducer);
//4、操作store里的状态
//当状态(数据)发生改变时,触发
store.subscribe(() => {
console.log(store.getState());
});
//修改、盗用
store.dispatch({ type: "doAdd" });
store.dispatch({ type: "doAdd" });
console.log(store.getState().num);
store.dispatch({ type: "appendSkill", skill: "uniapp" });
console.log(store.getState().skills);
store.dispatch({ type: "addCount" });
store.dispatch({ type: "addCount" });
console.log(store.getState().count);