React-Table v7.8.0 删除行后无法继续删除问题求助
问题原因
- 闭包导致旧值引用:
removeReservation函数直接引用cart变量但未用useCallback包裹,也未将cart设为依赖项,导致函数内部始终引用初始的cart值,首次删除后后续操作无法正确更新购物车。 - 对象引用匹配问题:使用
Set.delete(reservation)依赖对象引用完全相等,若传入的reservation与购物车中的对象不是同一引用,删除操作会失效。 - 列配置未响应更新:
columns的useMemo依赖为空数组,导致列中的removeReservation始终是组件首次渲染时的旧函数引用,无法响应后续函数更新。
解决方案
1. 修复removeReservation函数逻辑与闭包问题
用useCallback包裹函数,并改用ID过滤的方式删除项,避免引用匹配问题:
import { useCallback } from 'react'; // 在Context提供者组件中定义 const removeReservation = useCallback((reservation: Reservation) => { try { // 通过ID过滤删除,不受对象引用影响 const updatedCart = cart.filter(item => item.id !== reservation.id); if (updatedCart.length < cart.length) { setCart(updatedCart); } else { throw Error('Erro ao remover produto do carrinho'); } } catch (error) { console.log(error); } }, [cart]); // 依赖cart,确保函数始终引用最新的购物车数据
2. 更新React-Table列配置的依赖项
让列配置能响应removeReservation、units、workspaces的变化:
const columns = useMemo( () => [ { Header: 'Data', accessor: 'reservation_date', Cell:({cell: {value}}: any) => <> {moment(value).format('DD/MM/YYYY')} </> }, { Header: 'Periodo', accessor: 'period', Cell: ({cell: {value}}: Period) => <> {`${value.beginHour} - ${value.endHour}`} </> }, { Header: 'Unidade', accessor: 'period.unitId', Cell: ({cell: {value}}) => <> {units.find(el => el.id === value).name} </> }, { Header: 'Estação', accessor: 'workspace_id', Cell: ({cell: {value}}) => <> <Text> {workspaces.find(el => el.id === value).name} </Text> </> }, { Header: 'Preço', accessor: 'period.price', Cell:({cell: {value}}: any) => <> {new Intl.NumberFormat('pt-BR', {style: 'currency', currency:'BRL'}).format(value)} </> }, { Header: '', accessor: 'id', Cell:({cell}: any) => <> <Button size="sm" colorScheme="red" onClick={() => removeReservation(cell.row.original)} > Remover </Button> </> } ], [removeReservation, units, workspaces] // 加入依赖项,确保配置实时更新 );
3. 简化组件内的数据源管理(可选优化)
移除组件内多余的rowsData状态,直接使用props传入的reservations作为表格数据源:
// 移除以下代码: // const [rowsData, setRows] = useState(reservations) // useEffect(() => { // setRows([...reservations]) // }, [reservations]) // 直接使用props的reservations作为数据源 const data = useMemo(() => reservations, [reservations]);
完成以上修改后,每次删除操作都会正确更新购物车数据,React-Table会同步刷新,无需刷新页面即可多次执行删除操作。
内容的提问来源于stack exchange,提问作者Lucas Rodrigues
相关产品推荐
相关产品推荐

