安装rdux和redux-persist
npm i rdux npm i readux-persist
取值时
1.引入仓库
import { store } from '@/store'
const store=store.getSate()
修改时
store.dispatch({
type: IUserActionType.CHANGE,
payload: { token: res.data.token }
})
模块化存储rdux
创建store文件
里面创建index.tsx
import { createStore } from "redux";
import han from './reducers';
//配置数据的持久化效果
import { persistReducer, persistStore } from "redux-persist";
//导入需要配置的数据源,可以选择,storage,cookie,session等
import storage from "redux-persist/lib/storage";
// let store=createStore(han)
//定义配置的信息
const persitConfig = {
key:"root",
storage:storage,
// 如果不想将部分state持久化,可以将其放入黑名单(blacklist)中.黑名单是设置
// blacklist: ['ll']
}
//创建持久化的配置persist的信息
const persist_reducers = persistReducer(persitConfig,han);
//创建存储对象并且抛出对象
const store = createStore(persist_reducers);
const persistor = persistStore(store);
export { store, persistor };
//创建文件 reducers 并创建index.tsx
import { combineReducers } from "redux";
import user from "./user";
export default combineReducers({ user });
//并创建文件use并创建index.tsx
export interface IUser {
name: string;
token: string;
}
export interface IUserState {
user: IUser;
}
const initUserState: IUserState = {
/* state默认值 */
user: {
name: "普通用户",
token: "",
},
};
export enum IUserActionType {
/* Actions */
INIT,
CHANGE,
}
const user = (
state: IUserState = initUserState,
action: { type: IUserActionType; payload: any }
) => {
const { payload } = action;
switch (action.type) {
case IUserActionType.INIT:
return state;
case IUserActionType.CHANGE:
return { ...state, user: { ...state.user, ...payload } };
default:
return state;
}
};
export default user;
网友评论