加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

redux入门指南(二)

发布时间:2020-12-15 04:40:04 所属栏目:百科 来源:网络整理
导读:作者:Jogis 原文链接:https://github.com/yesvods/Blog/issues/7 转载请注明原文链接以及作者信息 第一篇介绍的是redux作为状态容器的核心思想,由 state 初始化,到 action 被分发而改变状态。之后的扩展都是围绕核心思想展开,也正得益于函数式编程等其

作者:Jogis
原文链接:https://github.com/yesvods/Blog/issues/7
转载请注明原文链接以及作者信息

第一篇介绍的是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就会产生更深嵌套的状态树。

未完待续...

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读