gpt4 book ai didi

javascript - 更新 React Redux 中的深层嵌套状态(标准化)

转载 作者:行者123 更新时间:2023-11-27 22:36:55 25 4
gpt4 key购买 nike

我正在尝试在 React/Redux 中创建一个航类搜索应用程序,在主屏幕中将显示我的所有航类结果,并在侧边栏中显示不同类型的过滤器作为复选框。 (例如,请参阅 this example

过滤器按类型分组,例如出发站、到达站、出发时间等。所有过滤元素都是在一个标准化嵌套状态下创建的,其中每个元素都具有以下属性:

"type": "airlines",           // this is the group type 
"checked": true, // will be switched true or false
"label": "Brittish Airways" // this is the display label

当我单击 React View 中的复选框之一时,将触发以下操作:

export function filterFlightOffers(item, index) {
return {
type: 'FILTER_FLIGHT_OFFERS',
grouptype,
id
}
}

我希望我的 redux reducer 更新状态(切换检查值)并返回新状态(例如不可变)。查看在线示例,我对解决方案做出了 react ,例如使用扩展运算符复制新状态,例如...使用切换的选中项声明并更新特定元素,例如{[action.id]:已检查,!已检查}。

但我就是无法让它工作,我想是因为我有一个很深的嵌套状态。因此我删除了操作和 reducer 的复杂性,并制作了一个简单的 jsfiddle ,它应该只是 console.log 一个新的不可变的'改变了状态。

有人可以帮我吗?

http://jsfiddle.net/gzco1yp7/4/

谢谢!

最佳答案

如果您所在的州看起来像这样:

{    
result: [1,2,3,4],
entities: {
searchitems: {
1: {
"type": "matchAirlines",
"checked": false,
"label": "Match airlines"
},
2: {
"type": "airlines",
"checked": true,
"label": "Air France"
},
3: {
"type": "airlines",
"checked": true,
"label": "Brittish Airways"
}
},
counts:
1: { "count": 2001 },
2: { "count": 579 },
3: { "count": 554 }
}
}
}

...您的 reducer 可能如下所示:

function reducer(state, action) {

switch (action.type) {
case 'FILTER_FLIGHT_OFFERS':
return {
...state,
entities: {
...state.entities,
searchItems: Object.keys(state.entities.searchItems).reduce((newItems, id) => {
const oldItem = state.entities.searchItems[id];
if (oldItem.type === action.groupType) {
newItems[id] = { ...oldItem, checked: id === action.id };
} else {
newItems[id] = oldItem;
}
return newItems;
}, {})
}
};
}

return state;
}

如果您使用combineReducers,这会变得更简单并为您的 searchItems 创建一个 reducer 。 Lodash 还可以简化事情:

import mapValues from 'lodash/mapValues';

function searchItemsReducer(state, action) {

switch (action.type) {
case 'FILTER_FLIGHT_OFFERS':
return mapValues(state, (oldItem, id) => (
oldItem.type === action.groupType
? { ...oldItem, checked: id === action.id };
: oldItem
));
}

return state;
}

关于javascript - 更新 React Redux 中的深层嵌套状态(标准化),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39027162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com