嵌套Redux减速器

JavaScript React.js

飞云

2020-04-07

是否可以组合嵌套有以下结构的减速器:

import 'user' from ...
import 'organisation' from ...
import 'auth' from ...
// ...

export default combineReducers({
  auth: {
    combineReducers({
        user,
        organisation,  
    }),
    auth,
  },
  posts,
  pages,
  widgets,
  // .. more state here
});

国家具有以下结构:

{
    auth: {
        user: {
            firstName: 'Foo',
            lastName: 'bar',
        }
        organisation: {
            name: 'Foo Bar Co.'
            phone: '1800-123-123',
        },
        token: 123123123,
        cypher: '256',
        someKey: 123,
    }
}

auth减速机具有结构:

{
    token: 123123123,
    cypher: '256',
    someKey: 123,   
}

所以也许散布算子很方便吗?...auth不确定 :-(

第4038篇《嵌套Redux减速器》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
老丝阿飞 2020.04.07

完美地结合使用嵌套的化径器combineReducers但是还有另一种非常有用的模式:嵌套化归约器。

const initialState = {
  user: null,
  organisation: null,
  token: null,
  cypher: null,
  someKey: null,
}

function authReducer(state = initialState, action) {
  switch (action.type) {
    case SET_ORGANISATION:
      return {...state, organisation: organisationReducer(state.organisation, action)}

    case SET_USER:
      return {...state, user: userReducer(state.user, action)}

    case SET_TOKEN:
      return {...state, token: action.token}

    default:
      return state
  }
}

在上面的示例中,authReducer可以将动作转发到状态organisationReduceruserReducer更新其状态的某些部分。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android