使用React从用户中删除项目后重新加载用户



使用React.Js当试图从列表末尾删除用户时,已删除的用户将被列表中的最后一项替换。只有在页面刷新时,被删除的用户才会真正消失,用户列表才会更新。后端可以工作,因为我可以删除用户,但我需要刷新才能看到新的更新

const Transition = React.forwardRef(function Transition(props, ref) {
return <Slide direction="up" ref={ref} {...props} />;
});

const combinedStyles = combineStyles(popupStyles, UserPageStyles);
export default function RemoveUser(props) {
const global = useContext(GlobalContext);
const [open, setOpen] = React.useState(false);
let org = {}
if (global.state.selectedOrg && Object.keys(global.state.selectedOrg).length !== 0) {
org = global.state.selectedOrg
} else if (global.state.defaultOrg && Object.keys(global.state.defaultOrg).length !== 0) {
org = global.state.defaultOrg
}
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
props.handleClose();
};
const handleSubmit = async () => {
let result = await global.api.removeAccount({
id: props.account._id,
role: global.state.user && global.state.user.document.roles[0] || '',
accountRole: props.type === 'patients' ? 'patient' : props.type === 'providers' ? 'doctor' : props.type === 'moas' ? 'oa' : props.type === 'admins' ? 'healthOrgAdmin' : props.type,
org: org._id,
username: props.account.username,
});
if (result && result.status === 200) {
handleClose();
props.refresh();
} else {
alert('Unable to remove account.');
}
}
const classes = combinedStyles();
return (
<div>
<ButtonBase className={props.className} onClick={handleClickOpen}> <Typography className={classes.typography}>Remove</Typography></ButtonBase>
<Dialog
open={open}
TransitionComponent={Transition}
keepMounted
onClose={handleClose}
aria-labelledby="alert-dialog-slide-title"
aria-describedby="alert-dialog-slide-description"
>
<DialogTitle className={classes.dialogTitle} id="alert-dialog-slide-title">Remove Account<IconButton onClick={handleClose} className={classes.dialogClose} children={<ClearIcon />} /> </DialogTitle>
<DialogContent>
<DialogContentText className={classes.contentText}>
Are you sure you want to remove {props.account.contact_name}'s account? You will not be able to revert this.
</DialogContentText>
</DialogContent>
<DialogActions className={classes.dialogAction}>
<Button onClick={handleClose} color="primary" className={classes.actionBtn}>
Cancel
</Button>
<Button onClick={handleSubmit} color="primary" className={classes.actionBtn}>
Yes
</Button>
</DialogActions>
</Dialog>
</div>
);
}

通常在删除请求完成后(使用200(,您必须设置一些新状态来触发重新渲染。你有州内所有用户的列表吗?你需要做一些类似setUsers(users.filter(u => u.id !== deletedUserId))的事情

有很多技巧可以重新渲染react组件:

  1. 状态更改时重新渲染组件任何时候React组件状态发生变化,React都必须运行render((方法。因此,您可能应该将用户列表影响到一种状态,以便在用户列表更改(状态(时重新呈现组件
  2. 道具更改时重新渲染组件
  3. 使用关键道具重新渲染
  4. 通过this.forceUpdate((强制重新渲染

看看React 中强制重新渲染的方法

最新更新