在switch语句(redux reducer)中更改数组的ids可以通过以下步骤实现:
以下是一个示例代码:
const initialState = {
ids: [1, 2, 3, 4, 5]
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'UPDATE_IDS':
return {
...state,
ids: state.ids.map(id => {
if (id === action.payload.oldId) {
return action.payload.newId;
}
return id;
})
};
default:
return state;
}
};
// 示例action
const updateIdsAction = {
type: 'UPDATE_IDS',
payload: {
oldId: 3,
newId: 6
}
};
// 调用dispatch方法触发action
dispatch(updateIdsAction);
在上述示例中,我们定义了一个名为"UPDATE_IDS"的action类型,它包含了需要更改的旧id和新id。在reducer中的相应case语句中,我们使用map方法遍历ids数组,如果元素的id等于旧id,则返回新id,否则返回原始id。最后,我们返回一个新的状态对象,其中的ids数组已经被更新。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云