Redux出现Object is not extensible错误,需实现对象属性动态增删
解决Redux中"Object is not extensible"错误并实现属性切换需求
Redux要求状态必须保持不可变性,你从useSelector获取的customAllAreas里的对象是被冻结的(不可扩展/修改),直接对原对象执行delete f.selected或f.selected = true会触发"Object is not extensible"错误。
正确的做法是创建原对象的副本,在副本上修改属性,再返回副本,确保不修改原状态对象:
const { customAllAreas } = useSelector((state) => state.AreasReducer); const saveArea = (area) => { const newFilteredAreas = customAllAreas?.map((f) => { if (f?._id === area?._id) { // 创建原对象的副本,避免修改原状态 const updatedArea = { ...f }; if (updatedArea.selected) { // 从副本中删除属性 delete updatedArea.selected; } else { // 给副本添加属性 updatedArea.selected = true; } return updatedArea; } return f; // 未匹配的对象直接返回原对象,无需复制 }); dispatch(AreasAction.setcustomeAddedAreas(newFilteredAreas)); };
关键说明:
- 使用扩展运算符
{ ...f }创建原对象的浅拷贝,确保操作的是新对象而非Redux store中的原对象 - 只对需要修改的对象进行拷贝,未匹配的对象直接返回,提升性能
- 保持Redux状态的不可变性是核心原则,这样Redux才能正确追踪状态变化,触发组件重新渲染
内容的提问来源于stack exchange,提问作者Andaman
相关产品推荐
相关产品推荐

