redux

时间:2016-04-22 04:46:14

标签: javascript redux

Redux 中构建与相关对象相关的状态对象的最佳做法是什么。

示例:

User有一个Organisation

使用上面的架构,我们还有一个组织列表,以下示例是一个好主意吗?

{
    user: {
        id: 1,
        organisation_id: 3,
        first_name: 'Andrew',
        last_name: 'McLagan',
        email: 'andrew@example.com',
        organisation: {
            name: 'Foo Bar Co.'
            suburb: 'Booklyn',
            phone: '123-123-000',
        },
    },
    orgnaisations: [
        {
            id: 1,
            name: 'Facebook'
            suburb: 'Booklyn',
            phone: '000-000-000',
        },
        {
            id: 2,
            name: 'Twitter'
            suburb: 'Manhattan',
            phone: '456-456-000',
        },
        {
            id: 3,
            name: 'Foo Bar Co.'
            suburb: 'Booklyn',
            phone: '123-123-000',
        },
        {
            id: 4,
            name: 'Some Org.'
            suburb: 'Bronx',
            phone: '642-642-000',
        },                      
    ]
}   

或者通过以下方式访问用户组织会更好:

const organisation = state.organisations[user.organisation_id];

1 个答案:

答案 0 :(得分:1)

我认为最好通过他们的ID访问用户组织。以下是组织州的可能方式:

{
  user: {
    id: 1,
    first_name: 'Andrew',
    last_name: 'McLagan',
    email: 'andrew@example.com',
    organization: 3,
  },
  organizations: {
    1: {id: 1, name: 'Facebook', suburb: 'Booklyn', phone: '000-000-000',},
    2: {id: 2, name: 'Twitter', suburb: 'Manhattan', phone: '456-456-000'},
    3: {id: 3, name: 'Foo Bar Co.', suburb: 'Booklyn', phone: '123-123-000'},
    4: {id: 4, name: 'Some Org.', suburb: 'Bronx', phone: '642-642-000'},
  }
}

使用vanilla Redux

如果您想获得当前用户及其组织,可以使用以下选择器:

function mapStateToProps(state) {
  return {
    user: state.user,
    organization: state.organizations[state.user.organization]
  }
}

使用其ID直接访问将获得性能提升。您仍然可以轻松查询所有存储的组织:

function mapStateToProps(state) {
  return {
    organizations: Object.values(state.organizations),
  }
}

使用重新选择

如果您关心表现,使用reselect将是一个巨大的胜利。第一步是定义选择器:

// Get a list of all organizations
const getAllOrganizations = createSelector(
  state => state.organizations,
  orgs => Object.values(orgs)
)

// Get the current user
const getUser = state => state.user

// Get the current user's organization
const getUserOrganization = createSelector(
  [
    state => state.user,
    state => state.organizations,
  ],
  (user, orgs) => orgs[user.organization],
)

您现在可以使用这些选择器更新mapStateToProps功能。上述两个将是:

// Get the current user and his organization
function mapStateToProps(state) {
  return {
    user: getUser(state),
    organization: getUserOrganization(state),
  }
}

// Get all organizations
const mapStateToProps = getAllOrganizations