Skip to content
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

拆分Recducer #16

Open
cqupt-yifanwu opened this issue Apr 8, 2017 · 0 comments
Open

拆分Recducer #16

cqupt-yifanwu opened this issue Apr 8, 2017 · 0 comments

Comments

@cqupt-yifanwu
Copy link
Owner

为什么要拆分

Reducer负责接收旧的State然后根据Action类型(利用switch case)来选择如何处理最后生成一个新的State返回。这里,Store接收到这个新的State之后会利用Store.subsricbe设置的监听函数来进行View层的更新。也就是说我们所有处理State的函数和逻辑都会放进Reducer里面,Reducer函数必定会非常的庞大。所以,这里我们要考虑对Reducer进行一个拆分。

如何拆分

这里我们使用阮一峰老师的一个例子:

const chatRducer = (state = defaultstate, action ()) => {
    const {type, payload} = action; // 利用结构赋值
    switch (type) {
        case ADD_CHAT:
          return Object.assign({}, state, {
            chatLog: state.chatLog.concat(payload)
          });
        case CHANGE_STATUS:
          return Object.assign({}, state, {
            statusMessage: payload
          });
        case CHANGE_USERNAME:
          return Object.assign({}, state, {
            userName: payload
          });
        default: return state;
    }
} 

在上面的代码中三段处理逻辑的关系不大,但是我们都写在了reducer函数里,我们就可以将reducer函数进行拆分。不同的函数负责处理不同的属性,然后再将他们合并成一个大的Reducer即可(其实拆分Reducer为的是逻辑上更加清晰,当编译了之后还是同样的效果)。

const chatReducer = (state = defaultState, action = {}) => {
  return {
    chatLog: chatLog(state.chatLog, action),
    statusMessage: statusMessage(state.statusMessage, action),
    userName: userName(state.userName, action)
  }
};

Redux提供了一个combineReducer方法,用于Reducer的拆分,只要定义各个子函数即可。

const chatReducer = combineReducers({
  chatLog,
  statusMessage,
  userName
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant