我使用 redux createEntityAdapter() 來管理我通過 createSlice() 創建的狀態,問題是我的狀態是嵌套的,我不知道如何更新它
這就是我的狀態
{ids: Array(1), entities: {…}, status: 'idle', error: null}
entities:
aLPii2RQz4IWitooG4lqB:
burger:
ingredients: Array(6)
0: {title: 'bread-tops'}
1: {title: 'cheese', Qty: 0}
2: {title: 'meatsss', Qty: 0}
3: {title: 'salad', Qty: 0}
4: {title: 'bacon', Qty: 0}
5: {title: 'bread-bottom'}
length: 6
[[Prototype]]: Array(0)
[[Prototype]]: Object
id: "aLPii2RQz4IWitooG4lqB"
[[Prototype]]: Object
[[Prototype]]: Object
error: null
ids: ['aLPii2RQz4IWitooG4lqB']
status: "idle"
[[Prototype]]: Object
例如,我想增加配料中的奶酪數量
burgerAdapter.updateOne(state, {
id,
changes: { burger: { ingredients: { } } },
});
我不知道我應該如何遍歷成分陣列以在“updateOne”屬性中找到奶酪
uj5u.com熱心網友回復:
在updateOne和updateManyCRUD方法只能做到淺合并。因此,如果您想更新嵌套更深的欄位,您有兩個選擇:
- 首先創建整個新
ingredients陣列 - 不要在此處使用 CRUD 方法 - 將更新邏輯撰寫為基于普通 Immer 的“變異”狀態更新
我個人會采用第二種方法。您已經擁有該專案的 ID,并且只有一件事需要更新。所以,這應該有效:
ingredientAdded(state, action) {
const {id, ingredientName} = action.payload;
const item = state.entities[id];
if (item) {
const ingredient = item.ingredients.find(ingredient => ingredient.title === ingredientName);
if (ingredient) {
ingredient.Qty = 1;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/351380.html
標籤:javascript 反应 还原
