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

Redux 中 combineReducers实现原理

发布时间:2020-12-14 04:15:50 所属栏目:大数据 来源:网络整理
导读:使用一个reducer const initialState = { id : 2,name : ‘myName‘,} import { createStore } from ‘redux‘; const reducer = function(state=initialState,action) { //... return state; } const store = createStore(reducer); 这种情况下,这个reduce
使用一个reducer
const initialState =
    {
        id          : 2,name    : ‘myName‘,}
    import { createStore } from ‘redux‘;
    const reducer = function(state=initialState,action) {
                    //...        
        return state;
    }
    const store = createStore(reducer);

这种情况下,这个reducer函数会对所有的action进行判断和处理,传入的state参数是整个store中的状态的全集。可能是这样:

{
                id          : 2,}

使用combineReducers 复合多个reducer

const user = (state = [],action) => {
        switch (action.type) {
            case ‘RENAME‘:
                //...
            default:
                return state;
        }
    }

const product = (state = [],action) => {
        switch (action.type) {
            case ‘SOLD‘:
                //...
            default:
                return state;
        }
    }

const reducers = combineReducers({
    user,product,});

const store = createStore(reducers);

这种情况下,每个reducer会对相关的action进行处理,返回与之相关的状态。(而实际实现是,combineReducers将所有reducer合并成立一个大的reducer)。

整个store的状态全集会是如下样子:

{
        user: {
            id: 0,name: ‘myNmae‘,},product: {
                id: 0,is_sold: 0,}
}

可以看出这是一个树形结构,每个reducer所处理的数据在自己的分支结构中。因此,每个reducer可以独立的编写,无需关注其他reducer的数据(state)处理方式。同样,dispatch的时候只要发送与之相关的内容即可。
譬如,写一个“我”的reducer:

const initialState =
        {
            name                 : null,displayName     : null,};

        const me = (state = initialState,action) =>
        {
            switch (action.type)
            {
                case ‘SET_ME‘:
                {
                    const { name,displayName } = action.payload;
                    return { name,displayName };
                }
                default:
                    return state;
            }
        };

//想要设置“我”的属性,只要:
store.dispatch({
    type    : ‘SET_ME‘,payload : { "jacky","小王"}
});

但是,事实上每个dispatch发出之后,所有reducer都会被调用一遍(只是大部分事不关己,直接返回自己的state),最终会返回一个完整的状态树,就像上面看到的样子。

编码建议

对于复杂的应用,可以编写多个reducer,每个reducer专注处理一类state。可以将多个reducer的实现放到一个文件里实现,也可以每个reducer使用一个单独的文件(便于分工)。

(编辑:李大同)

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

    推荐文章
      热点阅读