如何在 redux store 中设置与数据的关联
How to set up associations with data in redux store
我正在使用 redux 和一个类似于 here 的 api 中间件,它规范化响应数据并将结果存储在我的状态的实体字段中。因此,如果我向客户端点发出请求并返回如下内容:
customers: [{
id: 1,
name: 'Bob',
cards: [{id: 2, last4: '1234'}]
}]
我的商店看起来像:
{
entities: {
cards: {2: {id: 2, last4: '1234'}}
customers: {1: {id: 1, name: 'Bob'}}
}
}
我的问题是,重新建立这些协会的最佳方式是什么?这可以用选择器完成吗?
在 redux 中,只有 reducer 知道如何改变状态。在您的特定情况下,reducer 获取客户有效负载并将其添加到状态。
以一个客户作为有效负载的示例:
const action = {
customer: {
id: 11,
name: 'Joe',
cards: [{id: 22, last4: '2345'}]
}
};
const state = {
entities: {
cards: {2: {id: 2, last4: '1234'}},
customers: {1: {id: 1, name: 'Bob'}}
}
};
function reducerCustomer (state, action) {
const cards = action.customer.cards.reduce((cards, card) => {
cards[card.id] = card;
return cards;
}, {});
const customers = {
[action.customer.id]: {id: action.customer.id, name: action.customer.name}
};
return Object.assign({}, state, {
entities: Object.assign({}, state.entities, {
cards: Object.assign({}, state.entities.cards, cards),
customers: Object.assign({}, state.entities.customers, customers)
})
});
}
是的,在选择器中这样做听起来是个不错的计划。对于简单的情况,您可以直接在 mapStateToProps
中的组件中执行此操作(无论如何这几乎是一个选择器)。我还看到一些人在组件访问属性时懒惰地使用 normalizr 模式编写代码来对状态进行非规范化,这是您可能想要试验的东西。
我找到了这个库,它使处理 redux 存储中的相关数据变得非常容易。 redux-orm
我正在使用 redux 和一个类似于 here 的 api 中间件,它规范化响应数据并将结果存储在我的状态的实体字段中。因此,如果我向客户端点发出请求并返回如下内容:
customers: [{
id: 1,
name: 'Bob',
cards: [{id: 2, last4: '1234'}]
}]
我的商店看起来像:
{
entities: {
cards: {2: {id: 2, last4: '1234'}}
customers: {1: {id: 1, name: 'Bob'}}
}
}
我的问题是,重新建立这些协会的最佳方式是什么?这可以用选择器完成吗?
在 redux 中,只有 reducer 知道如何改变状态。在您的特定情况下,reducer 获取客户有效负载并将其添加到状态。
以一个客户作为有效负载的示例:
const action = {
customer: {
id: 11,
name: 'Joe',
cards: [{id: 22, last4: '2345'}]
}
};
const state = {
entities: {
cards: {2: {id: 2, last4: '1234'}},
customers: {1: {id: 1, name: 'Bob'}}
}
};
function reducerCustomer (state, action) {
const cards = action.customer.cards.reduce((cards, card) => {
cards[card.id] = card;
return cards;
}, {});
const customers = {
[action.customer.id]: {id: action.customer.id, name: action.customer.name}
};
return Object.assign({}, state, {
entities: Object.assign({}, state.entities, {
cards: Object.assign({}, state.entities.cards, cards),
customers: Object.assign({}, state.entities.customers, customers)
})
});
}
是的,在选择器中这样做听起来是个不错的计划。对于简单的情况,您可以直接在 mapStateToProps
中的组件中执行此操作(无论如何这几乎是一个选择器)。我还看到一些人在组件访问属性时懒惰地使用 normalizr 模式编写代码来对状态进行非规范化,这是您可能想要试验的东西。
我找到了这个库,它使处理 redux 存储中的相关数据变得非常容易。 redux-orm