-
Notifications
You must be signed in to change notification settings - Fork 227
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
重构: 拆分Redux store #17
Labels
enhancement
New feature or request
Comments
感谢建议! |
我下周有空可以写单元测试 |
@zjsth92 是否考虑这样的拆分方式: 关于 redux
state
目录结构分配
import { createStore } from 'redux';
import reducers from './reducers';
export default createStore(reducers);
// reducer 入口
import { combineReducers } from 'redux';
import user from './ducks/user';
import comment from './ducks/comment';
import article from './ducks/article';
// combineReducers
export default combineReducers({user, comment, article});
// Actions
export const types = {
LOGIN: 'userLogin', // 登录
LOGOUT: 'userLogout', // 登出
UPDATE: 'userUpdate', // 更新信息
COMMENT: 'comment', // 评论, 大概率移除
PUBLISH: 'publish', // 发布, 大概率移除
};
// state
const initialState: State = {
id: '', // key
bio: '',
url: '',
nickname: '',
username: '',
position: '',
isLogin: false,
};
// Reducer
export default function reducer(state = initialState, action: Action = {}) {
const { payload } = action;
switch (action.type) {
case types.LOGIN:
return Object.assign({}, state, payload);
case types.LOGOUT:
return Object.assign({}, state, initialState);
case types.UPDATE:
return Object.assign({}, state, payload);
case types.COMMENT:
return Object.assign({}, state);
case types.PUBLISH:
return Object.assign({}, state);
default:
return state;
}
};
// Action creaters
export const actions = {
userLogin: (payload: Payload) => ({ type: types.LOGIN, payload }),
userLogout: () => ({ type: types.LOGOUT }),
userUpdate: (payload: Payload) => ({ type: types.UPDATE, payload }),
// 文章id 评论内容 content
userComment: (payload: Payload) => ({ type: types.COMMENT, payload }),
// 文章title 文章内容 content
userPublish: (title: string, content: string) => ({ type: types.PUBLISH, payload: { title, content } }),
}; 这样方便默认导出 |
|
Why not consider importing Redux Toolkit? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
现在的Redux都是集中在
frontend/src/reducers/index.js
Line 39 in d752e26
建议可以做几个重构
拆分Reducer
Action type 添加 Namespace
同时由于Action会越来越多,对单一RedUC而对应的Action加Namespace进行隔离, 比如
frontend/src/actions/index.js
Lines 14 to 19 in 220a080
变成
需要多个Reducer同时做出反应的全局Action,保持命名不变。比如
frontend/src/actions/index.js
Lines 257 to 262 in 220a080
需要多个reducer更改State
frontend/src/reducers/index.js
Lines 478 to 498 in 53aa9ac
我们需要一个Higher Order Reducer, 读取namespace 将Action分配给对应的Reducer。同时Reducer可以写为
[Action Type]: (state, action) => state
的形式,比如这样的好处
switch
模式变量不能重复命名,只能用原始的var
定义重构方案
好处
可以更轻松支持分页这种更复杂的UI逻辑 #12
The text was updated successfully, but these errors were encountered: