如何在Redux中正确更新二维数组以触发React组件重渲染?
问题根因
你当前的写法仅对顶层state对象做了浅拷贝,obj.displayList仍指向原state中的数组引用,直接调用push方法是在原数组上修改,没有生成新的数组引用。Redux默认通过浅比较判断状态是否变化,检测不到本次更新,因此不会触发组件重渲染。
正确实现方案
Redux要求状态更新必须遵循不可变原则,即所有修改都要生成新的引用,不能直接修改原状态。
二维数组指定位置新增元素
对应你的需求,向displayList[parentIndex]末尾添加元素1,reducer写法如下:
case DISPLAY_LIST_ADD_NEW_RULE: const { parentIndex } = action.payload; return { ...state, // 拷贝外层displayList数组 displayList: state.displayList.map((innerArr, index) => { // 仅修改目标下标的内层数组 if (index === parentIndex) { // 展开内层数组生成新引用后添加新元素 return [...innerArr, 1]; } // 非目标项直接返回原引用,避免不必要的拷贝消耗 return innerArr; }) };
二维数组指定位置删除元素
如果需要删除displayList[parentIndex]下标为childIndex的元素,首先在action.payload中传入parentIndex和childIndex两个参数,reducer写法如下:
case DISPLAY_LIST_DELETE_RULE: const { parentIndex, childIndex } = action.payload; return { ...state, displayList: state.displayList.map((innerArr, index) => { if (index === parentIndex) { // 过滤掉要删除的元素,生成新的内层数组引用 return innerArr.filter((_, idx) => idx !== childIndex); } return innerArr; }) };
扩展说明
如果需要修改更深层级的属性(比如你状态中ruleGroup里的对象属性),需要逐层拷贝到要修改的层级,保证修改路径上所有节点的引用都是新的,才会被Redux检测到状态变化。
内容的提问来源于stack exchange,提问作者Aron
相关产品推荐
相关产品推荐

