在NextJS+ReactJS的AG Grid中仅展示isActive为True的行
实现AG Grid软删除逻辑:仅展示isActive为True的数据
一、在数据获取阶段过滤有效数据
直接在useEffect的fetch回调中,对后端返回的原始数据做过滤,只保留isActive为true的条目,再更新到rowData状态:
const [rowData, setRowData] = useState([]); const [colDefs, setColDefs] = useState([ {headerName: '', checkboxSelection: true}, {field: 'id', headerName:'ID', sortable: true, filter: true}, {field: 'course', headerName:'Golf Course', sortable: true, filter: true}, {field: 'city', headerName:'City', sortable: true, filter: true}, {field: 'state', headerName:'State', sortable: true, filter: true}, {field: 'isActive', headerName:'Is Active', } ]); useEffect(() => { fetch('http://localhost:3000/api/getgolfcourses') .then(result => result.json()) .then(rawData => { // 筛选出仅isActive为true的数据 const activeRows = rawData.filter(item => item.isActive === true); setRowData(activeRows); }) }, [])
二、实现软删除操作
当需要执行软删除时,先调用后端API将目标条目的isActive设为false,再更新前端数据:
方案1:重新拉取数据(保证前后端数据一致)
const handleSoftDelete = (rowId) => { // 调用后端接口更新isActive状态 fetch(`http://localhost:3000/api/updategolfcourse/${rowId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ isActive: false }) }) .then(() => { // 重新获取并过滤数据 fetch('http://localhost:3000/api/getgolfcourses') .then(res => res.json()) .then(rawData => { setRowData(rawData.filter(item => item.isActive === true)); }); }); }
方案2:本地状态直接更新(更高效,适合无并发场景)
const handleSoftDelete = (rowId) => { fetch(`http://localhost:3000/api/updategolfcourse/${rowId}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ isActive: false }) }) .then(() => { // 直接从本地数据中移除该条目 setRowData(prev => prev.filter(item => item.id !== rowId)); }); }
三、可选优化:隐藏isActive列
如果不需要在表格中展示isActive状态,可直接从列定义中移除该列,避免暴露内部逻辑:
const [colDefs, setColDefs] = useState([ {headerName: '', checkboxSelection: true}, {field: 'id', headerName:'ID', sortable: true, filter: true}, {field: 'course', headerName:'Golf Course', sortable: true, filter: true}, {field: 'city', headerName:'City', sortable: true, filter: true}, {field: 'state', headerName:'State', sortable: true, filter: true}, // 移除isActive列 ]);
内容的提问来源于stack exchange,提问作者Matthew S-B
相关产品推荐
相关产品推荐

