每次我删除useEffect并删除一个项目时,由于某种原因,action listResidents((都会运行两次,这只是一个例子,即使在其他组件中也会发生这种情况,我不知道它为什么会这样做。我试着自己解决这个问题,但每次删除或做某事时都没有发送。
function Residents() {
const RESIDENT_COLUMNS = useMemo(
() => [
{
Header: 'First Name',
accessor: 'fname',
Filter: ColumnFilter,
},
{
Header: 'Last Name',
accessor: 'lname',
Filter: ColumnFilter,
},
{
Header: 'E-Mail',
accessor: 'email',
disableFilters: true,
Filter: ColumnFilter,
},
{
Header: 'Phone',
accessor: 'phone',
disableFilters: true,
},
{
Header: 'Blk',
accessor: 'blk',
Filter: ColumnFilter,
},
{
Header: 'Lot',
accessor: 'lot',
Filter: ColumnFilter,
},
{
Header: 'Street',
accessor: 'street',
Filter: ColumnFilter,
},
{
Header: 'Actions',
accessor: 'actions',
Cell: props => {
return (
<ButtonGroup spacing={2}>
<IconButton
colorScheme="blue"
aria-label="Edit"
icon={<EditIcon />}
onClick={() => console.log(props.row.original._id)}
/>
<IconButton
colorScheme="red"
aria-label="Edit"
icon={<DeleteIcon />}
onClick={() => deleteHandler(props.row.original._id)}
/>
</ButtonGroup>
);
},
disableFilters: true,
},
],
[]
);
const dispatch = useDispatch();
const residentList = useSelector(state => state.residentList);
const { loading, error, residents } = residentList;
const residentDelete = useSelector(state => state.residentDelete);
const { success: successDelete } = residentDelete;
useEffect(() => {
dispatch(listResidents());
}, [dispatch, successDelete]);
const columns = RESIDENT_COLUMNS;
const data = useMemo(() => residents, [residents]);
const deleteHandler = id => {
dispatch(deleteResident(id));
};
return (
<Box p="2rem 8rem">
<ModalResident />
{loading ? (
<Loader />
) : error ? (
<Message status="error">{error}</Message>
) : (
<BaseTable data={data} columns={columns} />
)}
</Box>
);
}
export default Residents;
如果successDelete
变回false-也许调度listResidents((时会发生这种情况?-那就是为什么。
这将修复它:
useEffect(() => {
if(!successDelete) return;
dispatch(listResidents());
}, [dispatch, successDelete]);
^编辑:这个不会修复它,因为现在您不会在装载时调度listResidents
。
因此,效果是在删除后以粗略的方式调度listResidents
(但在装载时也可以(。最好在删除处理程序中执行。根据你是否使用thunks
,你可能可以这样做:
const deleteHandler = async id => {
await dispatch(deleteResident(id));
dispatch(listResidents())
};
并从效果上彻底摆脱了CCD_ 5依赖性。
或者,也许只是在thunk中调度一个listResidents
(同样,如果您使用的是thunk(来进行删除,并将其完全排除在组件代码之外。