Skip to content

redux入门指南(二) #7

Description

@yesvods

第一篇介绍的是redux作为状态容器的核心思想,由state初始化,到action被分发而改变状态。之后的扩展都是围绕核心思想展开,也正得益于函数式编程等其他扩展,redux成为目前最流行的react状态管理框架。

store

redux里面,store实例拥有四个方法:getState,dispatch,subscribe,replaceReducer
其中前两个是store的核心方法,分别用于获取状态以及改变状态。
subscribe用于订阅状态更改事件,每当store的状态改变后,订阅的函数就会被调用。
replaceReducer用于替换创建store的reducer,比如从页面A跳转到页面B后,仅仅需要替换reducer就可以让B页面使用所需的状态,在按需加载状态时候非常有用。

精简后的store创建代码非常简单:

function createStore(reducer, initialState){
    let currentState = initialState;
    return {
        getState: () => currentState,
        dispatch: action => {
            currentState = reducer(currentState, action)
        }
    }
}

reducer

reducer是一个简单的纯函数(currentState, action) => nextState
接收现在的状态以及action作为参数,根据action的类型以及信息,对state进行修改,返回最新的state

比如一个动物园有猫和狗,现在需要添加一些猫猫狗狗:

function cat(state = [], action){
    if(action.type === constant.ADD_CAT){
        state.push(action.cat);
        return state;
    }else {
        return state;
    }
}

function dog(state = [], action){
    if(action.type === constant.ADD_DOG){
        state.push(action.dog);
        return state;
    }else {
        return state;
    }
}
//添加Tom猫
dispatch({
    type: constant.ADD_CAT,
    cat: {
        name: 'Tom'
    }
});

//添加Jerry狗
dispatch({
    type: constant.ADD_DOG,
    dog: {
        name: 'Jerry'
    }
});

之前提及到的是单一数据源原则,一个应用应该只有一个数据源(state),但是一个reducer会产生一个state,那怎么把猫狗两个reducer合成一个呢。redux提供了工具函数combineReducers,把多个reducre进行结合。我们可以编写多个reducer函数,每个函数只专注于自己的状态修改(比如cat函数,只专注于对cat这个状态的修改,不管dog的状态)。
而且,通过combineReducers合成一个reducer后,可以继续使用combineReducers把合成过的reducers进行再次合成,这样就非常方便地产生一个应用状态树,这也是为什么reducr仅仅需要一个数据源,便可以管理大型应用整个状态的原因。

比如:

//homeAnimals就成为一个reducers
const homeAnimals = combineReducers({cat, dog});
// nextState:
// {
//   cat: [{...}],
//   dog: [{...}]
// }
const nextState = homeAnimals(state, action);

更高层级的状态树:

cons zoo = combineReducers(homeAnimals, otherAnimals);
// nextState:
// {
//   homeAnimals: {...},
//   otherAnimals: {...}
// }
const nextState = zoo(state, action);

合成的reducerzoo就会产生更深嵌套的状态树。

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions