****代码已更新****
我一直在试图弄清楚为什么在更改数据时不重新渲染钩子。我正在尝试找出答案,但是我找不到任何有关如何使用正确的useEffect
这是我正在使用的数据,我正在从商店致电用户
/* eslint-disable react/no-array-index-key */
/* eslint-disable no-shadow */
import React, { useState, useEffect } from 'react';
import clsx from 'clsx';
import PropTypes from 'prop-types';
import moment from 'moment';
import { useHistory } from 'react-router';
import { useSelector, useDispatch } from 'react-redux';
import { Link as RouterLink } from 'react-router-dom';
import PerfectScrollbar from 'react-perfect-scrollbar';
import { makeStyles } from '@material-ui/styles';
import {
Card, CardContent,
Table, TableHead,
TableRow, Avatar,
Typography, TableCell,
TableBody, CardActions,
TablePagination, Button, colors
} from '@material-ui/core';
import swal from 'sweetalert';
import Notifier from 'src/lib/Notifier';
import Label from 'src/components/Label';
import { updateUser, getUsers } from 'src/actions/userAction';
import ConfirmDialog from 'src/components/Dialog/ConfirmDialog';
import UsersApi from '../../../api/UsersApi';
import AccountApi from '../../../api/AccountApi';
const useStyles = makeStyles((theme) => ({
root: {},
content: {
padding: 0
},
inner: {
minWidth: 1050
},
nameContainer: {
display: 'flex',
alignItems: 'center'
},
avatar: {
marginRight: theme.spacing(2),
},
actions: {
justifyContent: 'flex-end'
},
button: {
display: 'flex',
borderBottom: 'none'
}
}));
function UsersTable(props) {
const {
className, users, match, ...rest
} = props;
const classes = useStyles();
const dispatch = useDispatch();
const history = useHistory();
const [rowsPerPage, setRowsPerPage] = useState(10);
const [page, setPage] = useState(0);
const [order, setOrder] = useState('asc');
const [orderBy, setOrderBy] = useState('lastModifiedDate');
const [account, setAccount] = useState([]);
const [isOpen, setIsOpen] = useState(false);
console.log('users-table', getUsers);
const handleDialogOpen = () => {
setIsOpen(true);
};
const handleDialogClose = () => {
setIsOpen(false);
};
const handleRequestSort = (event, property) => {
const isAsc = orderBy === property && order === 'asc';
setOrder(isAsc ? 'desc' : 'asc');
setOrderBy(property);
};
const handlePageChange = (event, newPage) => {
setPage(newPage);
};
const handleRowsPerPageChange = (event) => {
setRowsPerPage(parseInt(event.target.value, 10));
setPage(0);
};
const getAllUsers = useSelector((state) => state.userManagement.users);
const getUsers = () => dispatch(getUsers());
useEffect(() => {
AccountApi.getAccount().then((response) => {
setAccount(response.data);
})
.catch((error) => {
Notifier.error(error.response.title);
});
}, []);
useEffect(() => {
getUsers();
}, []);
useEffect(() => {
dispatch(getUsers());
}, []);
const toggleActive = (user) => () => dispatch(updateUser({
...user,
activated: !user.activated
}));
// const handleToggle = async (user) => {
// await dispatch(updateUser({ ...user, activated: !user.activated }));// update user
// dispatch(getUsers()); // get updated users
// };
const onDelete = async (id) => {
await UsersApi.deleteuser(id).then((response) => {
alert('Are you Sure you want to delete ?');
Notifier.success('User Deleted Successfully');
})
.catch((error) => {
Notifier.error(error.response.data.title);
});
};
return (
<Card
{...rest}
className={clsx(classes.root, className)}
>
<CardContent className={classes.content}>
<PerfectScrollbar>
<div className={classes.inner}>
<Table>
<TableHead>
<TableRow>
<TableCell>ID</TableCell>
<TableCell>Login</TableCell>
<TableCell>Email</TableCell>
<TableCell>Active </TableCell>
<TableCell>Language</TableCell>
<TableCell>Profiles</TableCell>
<TableCell>Created Date</TableCell>
<TableCell>Modified By</TableCell>
<TableCell>Modified Date</TableCell>
<TableCell>Actions</TableCell>
</TableRow>
</TableHead>
{getAllUsers.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage).map((user, data) => (
<TableBody>
<TableRow
className={classes.tableRow}
hover
key={user.id}
>
<TableCell>
{' '}
{user.id}
{' '}
</TableCell>
<TableCell>
<div className={classes.nameContainer}>
<Avatar
className={classes.avatar}
src={user.imageUrl}
/>
<Typography variant="body1">{user.login}</Typography>
</div>
</TableCell>
<TableCell>{user.email}</TableCell>
<TableCell>
{' '}
{user.activated ? (
<Button
color="primary"
onClick={toggleActive(user)}
variant="contained"
>
Activated
</Button>
) : (
<Button
onClick={toggleActive(user)}
variant="contained"
>
Deactivated
</Button>
)}
</TableCell>
<TableCell>{user.langKey}</TableCell>
<TableCell>
{user.authorities
? user.authorities.map((authority, res) => (
<div key={`user-auth-${data}-${res}`}>
<Label
color={colors.lightBlue[700]}
>
{' '}
{authority}
</Label>
</div>
))
: null}
</TableCell>
<TableCell>
{moment(user.createdDate).format('DD/MM/YYYY')}
</TableCell>
<TableCell>{user.lastModifiedBy}</TableCell>
<TableCell>
{moment(user.lastModifiedDate).format('DD/MM/YYYY')}
</TableCell>
<TableCell className={classes.button}>
<Button
color="primary"
size="small"
variant="contained"
component={RouterLink}
to={`user-management/${user.login}`}
>
<span>View</span>
</Button>
<Button
color="secondary"
size="small"
variant="contained"
component={RouterLink}
to={`user-management/${user.login}/edit`}
>
<span>Edit</span>
</Button>
<Button
color=""
size="small"
variant="contained"
component={RouterLink}
onClick={() => onDelete(user.login)}
disabled={account.login === user.login}
>
<span>Delete</span>
</Button>
</TableCell>
</TableRow>
</TableBody>
))}
</Table>
{/* {users.map((user) => (
<ConfirmDialog
title="Delete User?"
isOpen={isOpen}
handleClose={handleDialogClose}
onConfirm={() => onDelete(user.login)}
>
Are you sure you want to dlete
</ConfirmDialog>
))} */}
</div>
</PerfectScrollbar>
</CardContent>
<CardActions>
<TablePagination
component="div"
count={getAllUsers.length}
onChangePage={handlePageChange}
onChangeRowsPerPage={handleRowsPerPageChange}
page={page}
rowsPerPage={rowsPerPage}
rowsPerPageOptions={[5, 10, 25]}
/>
</CardActions>
</Card>
);
}
UsersTable.propTypes = {
className: PropTypes.string,
users: PropTypes.array.isRequired,
match: PropTypes.object.isRequired,
};
export default UsersTable;
答案 0 :(得分:0)
这可能会解决您的问题:
useEffect(() => {
const fetchData = () => {
setIsLoading(true);
dispatch(getUsers());
setIsLoading(false);
};
fetchData();
}, [isLoading]);
答案 1 :(得分:0)
使用它最初获取用户:
useEffect(() => {
setIsLoading(true);
dispatch(getUsers());
setIsLoading(false);
}, [dispatch]);
然后在此处,当用户执行操作时,您将拒绝更新用户。
const handleToggle = async(user) => {
await dispatch(updateUser({ ...user, activated: !user.activated }));// update user
dispatch(getUsers()); // get updated users
}
<TableCell>
{user.activated ? (
<Button
color="primary"
onClick={() => handleToggle(user)}
variant="contained"
>
Activated
</Button>
) : (
<Button
onClick={() => handleToggle(user)}
variant="contained"
>
Deactivated
</Button>
)}
</TableCell> )
答案 2 :(得分:-1)
在useEffect挂钩中,您调用[]等同于调用componentDidmount()
如果要调用fecthData 1次,则应使用:
useEffect(() => {
const fetchData = () => {
setIsLoading(true);
dispatch(getUsers());
setIsLoading(false);
};
fetchData();
}, []);
关于组件重新呈现,它将在状态更改后呈现,这意味着您商店中的用户发生更改,然后使用组件的它将重新呈现