如何通过使用React中的道具动态地设置儿童组件中的数据?

发布于 2025-01-21 07:04:27 字数 3462 浏览 2 评论 0 原文

我已经在

现在,我正在向后端发送请求,以将新记录添加到DB,我想在添加新记录后立即更新表,从后端获取所有项目。

这是我的parent app.js类,其中2个组件为 mainpanel tablefooterpanel

function App() {

  const [customers, setCustomers] = useState([]);
  
  useEffect(() => {
    const fetchPostList = async () => {
      const response = await service.getCustomerList();
      setCustomers(response.data);
    };
    fetchPostList()
  }, []);

  const refreshTableData = () => {
    const fetchPostList = async () => {
      const response = await service.getCustomerList();
      setCustomers(response.data);
    };
    fetchPostList()
  }
  return (
    <div className="App">
      <h1>Customer List</h1>
      <MainPanel param={customers}/>
      <TableFooterPanel funcParam={refreshTableData}/>
    </div>
  );
}

export default App;

我将刷新功能传递给tablefooterpanel,该函数具有一个按钮,该按钮添加了新的记录,并且此功能触发了此功能当添加新记录时。这是 tablefooterpanel

function TableFooterPanel(props) {

    const [firstName, setFirstName] = useState('');
    const [lastName, setLastName] = useState('');

    const addNewCustomer = (name, surname) => {
        service.addCustomer(name, surname);
        props.funcParam();
    }

    return (

        <>
            <Card className='buttonFooter'>
                <Form className='buttonFooter'>
                    <input type="text" placeholder="First Name" defaultValue={firstName} onChange={e => setFirstName(e.target.value)}></input>
                    <input type="text" placeholder="Last Name" defaultValue={lastName} onChange={e => setLastName(e.target.value)}></input>
                    <Button onClick={() => addNewCustomer(firstName, lastName)}>Add</Button>
                </Form>
            </Card>

        </>

    );

}
export default TableFooterPanel;

,我想刷新位于 mainpanel 中的表数据:

function MainPanel(props) {

  const [customers, setCustomers] = useState([]);
  
  const deleteCustomer = (id) => {
    service.deleteCustomerById(id);
  }

  return (
    <ReactBootStrap.Table striped bordered hover>
        <thead>
          <tr>
            <th>ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Delete</th>
          </tr>
        </thead>
        <tbody>
          {props.param &&
            props.param.map((item) => (
              <tr key={item.id}>
                <td>{item.id}</td>
                <td>{item.firstName}</td>
                <td>{item.lastName}</td>
                <td><Button onClick={() => deleteCustomer(item.id)} ><FontAwesomeIcon icon={faTrashRestore} /></Button></td>
              </tr>   
            ))}
        </tbody>
      </ReactBootStrap.Table>
  );
}

这里发生的是当我添加新记录时,表格数据不会动态变化,但是如果我添加了第二个数据,然后看到了先前的数据和更新表,但仍未显示最后添加的数据。如何刷新数据并将最新数据发送到 Mainpanel

export default MainPanel;

I have solved one of my problem in this question for passing function as param

Now I am sending request to backend to add new record to db and I want to update the table immediately after adding new record by getting all items from backend.

Here is my parent App.js class having 2 component as MainPanel and TableFooterPanel:

function App() {

  const [customers, setCustomers] = useState([]);
  
  useEffect(() => {
    const fetchPostList = async () => {
      const response = await service.getCustomerList();
      setCustomers(response.data);
    };
    fetchPostList()
  }, []);

  const refreshTableData = () => {
    const fetchPostList = async () => {
      const response = await service.getCustomerList();
      setCustomers(response.data);
    };
    fetchPostList()
  }
  return (
    <div className="App">
      <h1>Customer List</h1>
      <MainPanel param={customers}/>
      <TableFooterPanel funcParam={refreshTableData}/>
    </div>
  );
}

export default App;

I am passing refresh function to TableFooterPanel which has a button to add new record and this function is triggered when a new record is added. Here is TableFooterPanel

function TableFooterPanel(props) {

    const [firstName, setFirstName] = useState('');
    const [lastName, setLastName] = useState('');

    const addNewCustomer = (name, surname) => {
        service.addCustomer(name, surname);
        props.funcParam();
    }

    return (

        <>
            <Card className='buttonFooter'>
                <Form className='buttonFooter'>
                    <input type="text" placeholder="First Name" defaultValue={firstName} onChange={e => setFirstName(e.target.value)}></input>
                    <input type="text" placeholder="Last Name" defaultValue={lastName} onChange={e => setLastName(e.target.value)}></input>
                    <Button onClick={() => addNewCustomer(firstName, lastName)}>Add</Button>
                </Form>
            </Card>

        </>

    );

}
export default TableFooterPanel;

And I want to refresh table data which lies in MainPanel:

function MainPanel(props) {

  const [customers, setCustomers] = useState([]);
  
  const deleteCustomer = (id) => {
    service.deleteCustomerById(id);
  }

  return (
    <ReactBootStrap.Table striped bordered hover>
        <thead>
          <tr>
            <th>ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Delete</th>
          </tr>
        </thead>
        <tbody>
          {props.param &&
            props.param.map((item) => (
              <tr key={item.id}>
                <td>{item.id}</td>
                <td>{item.firstName}</td>
                <td>{item.lastName}</td>
                <td><Button onClick={() => deleteCustomer(item.id)} ><FontAwesomeIcon icon={faTrashRestore} /></Button></td>
              </tr>   
            ))}
        </tbody>
      </ReactBootStrap.Table>
  );
}

What happens here is when I add a new record, the table data is not changing dynamically, but if I add second data then I sees the previous data and updating table but still not showing the last added data. How can I refresh data and send latest data to MainPanel?

export default MainPanel;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

九八野马 2025-01-28 07:04:27

您的问题与本节有关:

const addNewCustomer = (name, surname) => {
  service.addCustomer(name, surname);
  props.funcParam();
}

看起来您正在调用refresh函数( props.funcparam()),然后 addcustomer 服务已被调用(因为这是一个 Promise )。这会导致您的获取在更新现有数据之前开始获取现有数据。

您需要使函数异步,然后等待这样:

const addNewCustomer = async (name, surname) => {
  await service.addCustomer(name, surname);
  props.funcParam();
}

现在您的功能将等待 service.Addcustomer 才能完成执行,然后再执行刷新量。

Your problem is with this section:

const addNewCustomer = (name, surname) => {
  service.addCustomer(name, surname);
  props.funcParam();
}

It looks like you are calling the refresh function (props.funcParam()) before the addCustomer service is finished being called (since this is a Promise). That is causing your fetch to start fetching the existing data BEFORE it is updated.

You'll need to make the function asynchronous and then await it like this:

const addNewCustomer = async (name, surname) => {
  await service.addCustomer(name, surname);
  props.funcParam();
}

Now your function will wait for service.addCustomer to finish executing before executing the refresh fuction.

总攻大人 2025-01-28 07:04:27

假设 service.addcustomer(名称,姓氏)是一个异步调用,它将数据发布到服务器。然后,您需要将 addNewCustomer 方法放入异步,并等待此通话的响应,一旦您得到响应,您需要致电 props.funcparam()才能获得服务器的最新数据。

Assuming service.addCustomer(name, surname) is an async call and it posts data to server. Then you need to put addNewCustomer method into an async and await for the response of this call, once you get the response, you need to call props.funcParam() to get the latest data from server.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文