有人能帮我在redux更新二维数组吗?



我看到我的商店正在正确更新,但反应没有呈现组件。请让我知道如何正确更新二维数组,以便react渲染它。

mainReducer.js

const initialState = {
displayList: [[1]],
ruleGroup: [[{ field: "Theme", condition: "Equals", criteria: "Offers" }]],
};
const reducer = (state = initialState, action) => {
let obj = null;
switch(action.type){
case DISPLAY_LIST_ADD_NEW_RULE:
parentIndex = action.payload.parentIndex;
obj = { ...state };
obj.displayList[parentIndex].push(1);
return obj;
}
}

因此,我必须将值1(在我的例子中)推送到二维数组中的特定位置。有人能告诉我如何正确地做到这一点吗?如果你能告诉我如何删除,我将不胜感激。

我会尝试这样做

case DISPLAY_LIST_ADD_NEW_RULE:
return {
...state,
displayList: state.displayList.map((list, index) => {
return index === action.payload.parentIndex ? [...list, 1] : list
}),
}

很难说还有什么地方出了问题。链接到codesandbox或git repo可能会有帮助

有更多的东西来评估这里到底发生了什么…但也许这有帮助

const initialState = {
displayList: [[1]],
ruleGroup: [[{ field: "Theme", condition: "Equals", criteria: "Offers" }]],
};
function myCustomFunction(index, arr){
// see stackoverflow link below
}
const reducer = (state = initialState, action) => {
let obj = null;
switch(action.type){
// this case type wasn't defined anywhere, made it a string'
case 'DISPLAY_LIST_ADD_NEW_RULE':
const parentIndex = action.payload.parentIndex;
const newDisplayInsert = myCustomFunction(parentIndex, state.displayList)
// see related stackoverflow article
return {...state, displayList: newDisplayInsert };

default: return state
}
}

我建议在reducer之外有一个自定义操作来处理这个

如何在redux reducer中更新2D数组中的值?

最新更新