简体   繁体   English

子组件更新成功时如何从子组件调用父组件中的function

[英]How to call a function in a parent component from a child component when there is a successful update in child component

I have two components.我有两个组件。 My parent component, IntakeDetails, calls the child component, ActionsTab, within a TabPanel.我的父组件 IntakeDetails 在 TabPanel 中调用子组件 ActionsTab。 The Actions component contains a table and Dialogs. Actions 组件包含一个表格和对话框。 When I close any Dialog in Actions, I want to call a function in IntakeDetails called fetchDetails .当我关闭 Actions 中的任何 Dialog 时,我想在 IntakeDetails 中调用 function 名为fetchDetails How would I go about doing this?我将如何 go 这样做?

fetchDetails pulls some crucial data that is changed in backend api's when certain criteria in ActionsTab are met.当满足 ActionsTab 中的某些条件时, fetchDetails会提取后端 api 中更改的一些关键数据。 I want to call fetchDetails every time there is a successful update in ActionsTab.每次在 ActionsTab 中成功更新时,我都想调用fetchDetails

This is a basic overview of my code.这是我的代码的基本概述。

IntakeDetails摄入细节

export default function IntakeDetails2() {
    const [details, setDetails] = useState("");
    const [busy, setBusy] = useState(false);
    const [value, setValue] = useState(1);  // Tab panel index

    const fetchDetails = async () => {
        setBusy(true);
        if (value === 1) {
            const response = await fetch(`/api/fiscalyears/${fy}/intakes/${params.id}/details2`);
            const detailsResp = await response.json();
            setDetails(detailsResp);
        }
        setBusy(false);
    };

....
    return (
            <Tabs value={value} onChange={handleChange} aria-label="basic tabs example">
                <Tab label="Solutioning" className={classes.tabs} />
                <Tab label="Actions" className={classes.tabs} disabled={details?.IntakeID === 0} />
            </Tabs>
            <TabPanel value={value} index={1}>
                ....
            </TabPanel>
            <TabPanel value={value} index={4}>
                <ActionsTab />
            </TabPanel>
    );
}

ActionsTab动作选项卡

function ActionsTab() {
...
    const updateAction = async (e) => {
        e.preventDefault();
        const updateResponse = await fetch(`/api/actions/${action.Id}`, {
            method: "PATCH",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(action),
        });
        const updateActionResp = await updateResponse.json();
        if (updateResponse.ok) {
            setSuccessOpen(true);
            // I would like to call the fetchDetails() function here 
        } else {
            setErrorMessage(updateActionResp?.error);
            setErrorOpen(true);
        }
    };

    const onMessageClose = () => {
        setSuccessOpen(false);
        fetchActions();
    };
}

Add your callback as a prop in ActionsTab , and pass it from IntakeDetails .ActionsTab回调添加为道具,并从IntakeDetails传递它。

Example:例子:

function ActionsTab(props) {  // props get passed as the 1st argument from parent
  // ...

  const updateAction = async (e) => {
        e.preventDefault();
        const updateResponse = await fetch(`/api/actions/${action.Id}`, {
            method: "PATCH",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(action),
        });
        const updateActionResp = await updateResponse.json();
        if (updateResponse.ok) {
            setSuccessOpen(true); 
            // add your function call here - this will call the func
            // that was passed from the parent
            props.onUpdate() // you can pass arguments here if you want
        } else {
            setErrorMessage(updateActionResp?.error);
            setErrorOpen(true);
        }
    };

  // ...
}

And then:接着:

export default function IntakeDetails2() {

  // ...

  return (
    // ...
    <TabPanel value={value} index={4}>
      {/* pass the function you want to call when ActionsTab triggers update */}
      <ActionsTab onUpdate={() => fetchDetails()} />
    </TabPanel>
  )
}

The simplest thing you can do is to pass the fetchDetails function as property to your ActionsTab ->您可以做的最简单的事情是将fetchDetails function 作为属性传递给您的ActionsTab ->

<TabPanel value={value} index={4}>
    <ActionsTab fetchDetails={fetchDetails} />
</TabPanel>

After you used destructure it from your props ->从道具中使用解构后->

function ActionsTab({ fetchDetails }) {

you can use it within updateAction ->您可以在updateAction -> 中使用它

if (updateResponse.ok) {
    setSuccessOpen(true);
    // I would like to call the fetchDetails() function here 
    await fetchDetails()
}

FYI: I see that you want Error handling.仅供参考:我看到你想要错误处理。 I suggest you wrap your axios call in try and catch to handle any error while fetching.我建议您将 axios 调用包装在 try 和 catch 中以处理获取时的任何错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM