redux入门指南(二)

前端之家收集整理的这篇文章主要介绍了redux入门指南(二)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

作者: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创建代码非常简单:

@H_404_37@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

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

@H_404_37@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; } } @H_404_37@//添加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仅仅需要一个数据源,便可以管理大型应用整个状态的原因。

比如:

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

更高层级的状态树:

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

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

未完待续...

猜你在找的React相关文章