学习redux,鉴于官方switch代码繁琐,官方文档提示“
究竟使用带有标记位的同一个 action,还是多个 action type 呢,完全取决于你。这应该是你的团队共同达成的约定。使用多个 type 会降低犯错误的机率,但是如果你使用像 redux-actions 这类的辅助库来生成 action 创建函数和 reducer 的话,这就完全不是问题了。
”
故整理使用方式如下
createActions
// src/redux/action/login.ts
import { IAppUser } from '../../pages/login.type';
import { createActions } from 'redux-actions';
export const LOGIN_ACTION = {
LOGIN: 'login',
LOGOUT: 'logout',
};
const loginActions = createActions({
[LOGIN_ACTION.LOGIN]: (appUser: IAppUser) => appUser,
[LOGIN_ACTION.LOGOUT]: () => null,
});
export default loginActions;
reducer
// src/redux/reducer/login.ts
import { LOGIN_ACTION } from '../action/login';
import { assign } from 'lodash';
import { Action, handleActions as createReducers } from 'redux-actions';
import { IAppUser } from 'pages/login.type';
const defaultState = {
// defautl value 不能为null
appUser: {},
};
export default createReducers(
{
// payload 参数名固定,类型推导
[LOGIN_ACTION.LOGIN]: (state, { payload }: Action<IAppUser>) => ({
...state,
appUser: payload,
}),
// 异常处理
[LOGIN_ACTION.LOGOUT]: {
next(state) {
return {
...state,
appUser: {},
};
},
throw(state) {
return state;
},
},
},
defaultState
);
store
// src/redux/store.ts
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import thunk from 'redux-thunk';
import loginReducer from './reducer/login';
export const rootReducer = combineReducers({
login: loginReducer,
});
const store = createStore(
rootReducer,
compose(
applyMiddleware(thunk),
(window as any).__REDUX_DEVTOOLS_EXTENSION__ &&
(window as any).__REDUX_DEVTOOLS_EXTENSION__()
)
);
export type RootState = ReturnType<typeof rootReducer>;
export type AppDispatch = typeof store.dispatch;
export default store;
tsx
import { connect, ConnectedProps } from 'react-redux';
import { Button } from 'antd';
import { RootState } from 'redux/store';
import actions, { LOGIN_ACTION } from 'redux/action/login';
const mapState = (state: RootState) => ({
appUser: state.login.appUser,
});
const mapDispatch = {
onLogin: actions[LOGIN_ACTION.LOGIN],
onLogout: actions[LOGIN_ACTION.LOGOUT],
};
const connector = connect(mapState, mapDispatch);
type PropsFromRedux = ConnectedProps<typeof connector>;
const List = (props: PropsFromRedux) => {
return (
<div>
{JSON.stringify(props.appUser)}
<Button onClick={() => props.onLogin({ id: '1', userName: '123' })}>
修改appUser
</Button>
<Button onClick={props.onLogout}>清空appUser</Button>
</div>
);
};
export default connector(List);
网友评论