javascript - 渲染没有更新?
问题描述
当我想删除一个用户时,我想显示一个确认弹出窗口。所以当我按下删除按钮时,我希望我的弹出窗口出现。我所做的是我有一个根据海报变量呈现的弹出窗口。如果它是真的,那么我会显示,如果它是假的,我不会显示。从逻辑上讲,当我按下删除按钮时,我应该显示我的弹出窗口,所以我修改了变量并将其设置为 true,但我的弹出窗口没有显示
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
import ListItemText from '@material-ui/core/ListItemText';
import AuthentificationService from "../../api/AuthentificationService"
import IconButton from '@material-ui/core/IconButton';
import DeleteIcon from '@material-ui/icons/Delete';
import Modal from "../Modal/Modal"
const useStyles = makeStyles(theme => ({
root: {
width: '100%',
maxWidth: 360,
backgroundColor: theme.palette.background.paper,
},
}));
export default function CheckboxList(props) {
const classes = useStyles();
let deleteIt = false;
const [checked, setChecked] = React.useState([0]);
const handleToggle = value => () => {
const currentIndex = checked.indexOf(value);
const newChecked = [...checked];
if (currentIndex === -1) {
newChecked.push(value);
} else {
newChecked.splice(currentIndex, 1);
}
setChecked(newChecked);
};
const deleteUser = value => () => {
AuthentificationService.deleteUser(value.id)
.then((data) => {
console.log(data);
}) .catch((error) => {
})
}
const confirmationDeleteUser = value => () => {
deleteIt = true;
}
return (
<List className={classes.root}>
{props.response.map( test => {
if (props.response.length <= 1) {
} else {
return (
<ListItem key={test} role={undefined} dense button onClick={handleToggle(test)}>
<ListItemText primary={`${test.email}`}/>
<ListItemSecondaryAction>
<IconButton edge="end" aria-label="delete" onClick={confirmationDeleteUser(test)}>
<DeleteIcon />
<div>
{deleteIt === false ? "" : <Modal title="Confirmation" message="hey"/>}
</div>
</IconButton>
</ListItemSecondaryAction>
</ListItem>
);
}
})}
</List>
);
}
当我的 deleteIt 变量等于 true 时,我想显示我的弹出窗口。为什么它不起作用?我不明白什么?
解决方案
仅当作为 prop 或组件状态一部分的值发生更改时,React 才会重新渲染。在您的情况下,该deleteIt
变量不是状态变量,因此即使您使用 更改它confirmationDeleteUser
,您的组件也不会重新渲染以触发弹出窗口。
尝试使用来定义您的变量useState
,如下所示:
const [deleteIt, setDeleteIt] = useState(false);
并将您的代码confirmationDeleteUser
更改为deleteIt
如下所示:
setDeleteIt(true);
这应该让事情朝着正确的方向发展。
推荐阅读
- vb.net - 根据 datagridview 行选择从 SQLite 获取数据
- r - 如何将预测函数用于存储在小标题中作为列的线性模型
- regex - 正则表达式:至少匹配给定字符串或模式列表中的*两个*?
- nix - 如何在商店中找到一个派生路径,从编译的包路径开始?
- c# - .net core 2.2 应用程序的 JWT 身份验证不使用身份
- c - Scanf 过滤输入
- python - 需要 userInput_1 更新
- reactjs - 当用户是管理员时,在评论模块中更改芯片(材料-UI)的不同背景颜色
- angular - 仅在 1 个字段上需要解决范围比较(<、<=、>、>=)的火力基础限制
- c# - 在多租户环境中更快的 NHibernate 加载