如何不直接修改状态重构React代码?使用扩展运算符时页面卡顿求解
React代码重构方案(避免直接修改状态+解决卡顿)
首先,你原代码的核心问题是直接修改了state数组(workforcePlanList[index] = data、splice),这违反了React状态的不可变性原则,会导致状态更新不被React检测到,还可能引发状态不一致的问题。针对你的需求,重构方案如下:
1. 抽离重复的过滤逻辑
把两处重复的员工过滤逻辑抽成单独函数,减少代码冗余:
const getActiveEmployeeWithoutAction = (list) => { return list.filter(x => x.Employee.StatusEnum === EmployeeStatusEnum.Active && !x.IsAdmin && !x.IsCreate && !x.IsView ); };
2. 用不可变方式更新数组
不再直接修改原state数组,而是创建新数组后更新:
重构changeFromGridCard:
const changeFromGridCard = (data, index) => { // 用map创建新数组,只替换目标索引的元素 const updatedList = workforcePlanList.map((item, i) => i === index ? data : item ); setWorkforcePlanList(updatedList); };
重构onClose:
const onClose = (employeeId, index) => { // 用filter创建新数组,排除目标索引的元素 const updatedList = workforcePlanList.filter((_, i) => i !== index); setWorkforcePlanList(updatedList); };
3. 用useMemo推导saveDisable状态(解决卡顿)
你之前手动调用setSaveDisable可能导致重复计算,改用useMemo缓存计算结果,只有依赖变化时才重新计算:
// 替换原有的const [saveDisable, setSaveDisable] = useState(...) const saveDisable = useMemo(() => { const activeWithoutAction = getActiveEmployeeWithoutAction(workforcePlanList); return isSameList() || activeWithoutAction.length > 0; }, [workforcePlanList]); // 依赖数组变化时才重新计算
重构后完整代码示例
import { useState, useMemo } from 'react'; const [workforcePlanList, setWorkforcePlanList] = useState<WorkForcePlanPermissionType[]>([]); const getActiveEmployeeWithoutAction = (list) => { return list.filter(x => x.Employee.StatusEnum === EmployeeStatusEnum.Active && !x.IsAdmin && !x.IsCreate && !x.IsView ); }; const saveDisable = useMemo(() => { const activeWithoutAction = getActiveEmployeeWithoutAction(workforcePlanList); return isSameList() || activeWithoutAction.length > 0; }, [workforcePlanList]); const changeFromGridCard = (data, index) => { const updatedList = workforcePlanList.map((item, i) => i === index ? data : item ); setWorkforcePlanList(updatedList); }; const onClose = (employeeId, index) => { const updatedList = workforcePlanList.filter((_, i) => i !== index); setWorkforcePlanList(updatedList); };
关键改进点
- 严格遵循React状态不可变性,所有数组更新都创建新数组,确保React能正确检测状态变化触发渲染。
- 抽离重复逻辑,提升代码可维护性。
- 用
useMemo缓存计算结果,避免每次数组更新都重复执行过滤和判断,缓解页面卡顿。
内容的提问来源于stack exchange,提问作者Abin
相关产品推荐
相关产品推荐

