reactjs - Reactjs将数据从孩子传递给父母
问题描述
添加没有问题,因为我成功地将数据添加到我的数据库中,但问题是需要在获取更新的数据之前刷新页面。这是我到目前为止所做的代码,这是当前的错误,我是否遗漏了代码中的某些内容?请帮忙
笔记:
子组件会添加数据,父组件会显示子组件插入的最新数据
父母
const OvertimeType = () => {
const [reRender, setRerender] = useState(false);
....
const fetchData = async () => {
const response = await getDepartmentData('All', 100, 0);
response.data.map(function(u){
.....
})
}
useEffect(() => {
fetchData();
}, [reRender]);
const HandleAdd = (val) =>{
setRerender(val);
}
return (
<CustomToolbar sendToParent={HandleAdd()}/>
)
...
}
//
孩子
class CustomToolbar extends React.Component {
state = false;
HandleAdd = () => {
Swal.fire({
title: 'Add Over Time',
text: "Input overtime name below.",
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Save',
html: generateInputForms({
strname: '',
intsequence: ''
}),
preConfirm: () => {
let strname = document.getElementById('strname').value;
let intsequence = document.getElementById('intsequence').value;
if (!strname) {
Swal.showValidationMessage('This field is required.')
}
if (!intsequence) {
Swal.showValidationMessage('This field is required.')
}
return {
strname: document.getElementById('strname').value,
intsequence: document.getElementById('intsequence').value
}
}
}).then((result) => {
if (result.isConfirmed) {
let request = {
strname:document.getElementById('strname').value,
intsequence:document.getElementById('intsequence').value
}
addDepartment(request).then(res =>{
if (res.status == 200){
Swal.fire({
icon: 'success',
title: 'Over Time',
text: 'New Data has been added successfully.',
}).then(res => {
this.sendToParent(res);
})
}else{
Swal.fire({
icon: 'error',
title: 'Oops',
text: 'Something went wrong.',
})
}
})
}
})
}
render() {
const { classes } = this.props;
return (
<React.Fragment>
<Tooltip title={"Add"}>
<Button
variant="contained"
onClick={this.HandleAdd}
className={classes.button}
startIcon={<AddIcon className={classes.addIcon} style={{color: '#fff',}} />}
>
Add
</Button>
</Tooltip>
</React.Fragment>
);
}
}
解决方案
问题可能是你传递函数的方式
<CustomToolbar sendToParent={HandleAdd()}/>
回调函数应该像这样发送,不带括号:
<CustomToolbar sendToParent={HandleAdd}/>
推荐阅读
- asp.net-web-api - 使用 asp.net web api 连接到 Ldap 并验证用户
- sql-server - 如何从临时表名中选择,传递给存储过程?
- java - 在 Android Pie 中修剪 AlertDialog
- java - 在soap ui中创建测试套件和测试用例需要什么。我们可以直接测试请求。请解释
- angular - 错误:发出 POST 请求时,无法从同步测试中调用 process.nextTick
- java - Problem with inserting/appending comment before root node and after prolog with org.w3c.dom
- reactjs - Firefox浏览器无法保存用户名和密码
- php - Laravel - 一个 CMS / 多个站点
- c# - 如何使用本机 MongoDB.Driver 将 mongo 脚本转换为纯 C# 代码?
- jmeter-5.0 - 每个场景都需要登录/注销进行性能测试?