1.约束store库,框定结构及属性名
```javascript
export interface ICurrentUser {
character: string[];
name: string;
phone: string;
user_id: number;
}
export interface UserModelState {
currentUser: ICurrentUser;
}
export interface UserModelType {
namespace: 'user';
state: UserModelState;
effects: {
fetchCurrent: Effect;
};
reducers: {
saveCurrentUser: Reducer<UserModelState>;
addCurrentUser: Reducer<UserModelState>;
};
subscriptions: { setup: Subscription };
2.根据约束创建 user 数据管理库
const UserModel: UserModelType = {
namespace: 'user',
state: {
currentUser: {
name: '',
user_id: 0,
character: [],
phone: '',
},
},
effects: {
*fetchCurrent(_, { call, put }) {
const response = yield call(queryCurrent);
yield put({
type: 'saveCurrentUser',
payload: response.data,
});
setAuthority(response.data.character);
},
},
reducers: {
saveCurrentUser(state, action) {
return { ...state, currentUser: action.payload };
},
addCurrentUser(state, action) {
return { ...state, currentUser: action.payload };
},
},
subscriptions: {
setup() {},
},
};
``
2.1.namespace 确定仓库名
namespace: 'user',
使用:
2.2.state 初始化数据
state: {
currentUser: {
name: '',
user_id: 0,
character: [],
phone: '',
},
},
2.3.effects
put:用于触发 action 。
call:用于调用异步逻辑,支持 promise 。
2.3.1 发起请求,请求到user数据
const response = yield call(queryCurrent);
2.3.2 将获取到的数据传入action里
2.3.3 调用util里的存localStorage的方法
2.4通过reducer改变state
3.使用 useSelector
const currentUser = useSelector(({ user }: { user: UserModelState }) => user.currentUser);
useSelector是获取redux数据管理库的方法,
user是状态管理库名称,
UserModelState 是user的约束
currentUser是数据管理器中存的数据
4.存储 useDispatch
const dispatch = useDispatch();
if (dispatch) {
dispatch({
type: "user/fetchCurrent",
payload: { data },
});
}
type:调用的存储函数(仓库名/effect中的函数名)
payload:要存的数据