首页 > 解决方案 > 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>
    );
  }
}

标签: reactjs

解决方案


问题可能是你传递函数的方式

    <CustomToolbar sendToParent={HandleAdd()}/>

回调函数应该像这样发送,不带括号:

<CustomToolbar sendToParent={HandleAdd}/>

推荐阅读