Skip to content

Latest commit

 

History

History
78 lines (53 loc) · 2.04 KB

CombineReducers.md

File metadata and controls

78 lines (53 loc) · 2.04 KB

combineReducers

使用tip

  • 每一个reducer会根据combineReducers中设置的key在处理中获得一个独立subState
  • 每一个reducer处理subState的时候不要返回nil
  • 所有未匹配到的action,必须把它接收到state原封不动返回

编写Reducer

Reducer SubReducer01 = ^SubState01 * (id<Action> action, SubState01 *state) {

    if (state == nil) {
    	// 需要处理nil 返回初始值
        SubState01 *nextState = [SubState01 new];
        return nextState;
    }

    if ([state isKindOfClass:[SubState01 class]]) {
        // do something
    }

    return state;
};

Reducer SubReducer02 = ^ SubState02 * (id<Action> action, SubState02 *state) {

    if (state == nil) {
    // 需要处理nil 返回初始值
        SubState02 *nextState = [SubState02 new];
        return nextState;
    }

    if ([state isKindOfClass:[SubState02 class]]) {
        // do something
    }

    return state;
};

使用combineReducers

#import <Redux/Combine.h>

Reducer reducer = combineReducers(@{kSubState01: SubReducer01,
                                    kSubState02: SubReducer02,
                                    ...
                                   });
Store *store = [[Store alloc] initWithReducer:reducer
                                      state:nil
                                middlewares:@[middleware01, middleware02, ...]];

回调的地方

- (void)updateState:(CombinedState *)state {
    // 依次处理每个sub state
    SubState01 subState01 = [state subStateForKey:kSubState01];
    ...
}

或者如果不想回调CombinedState,可以再subscribe的时候传入transForm,可以参见ComplexCounter Demo