React中如何将子组件变更同步至父组件(或刷新父组件)
解决子组件编辑后父组件数据不同步的问题
核心问题是你仅调用API更新了后端数据,但未将更新后的客户数据同步到SaleContext的状态中,导致父组件无法感知数据变化,仍显示旧内容。以下是具体修复步骤:
1. 传递状态更新方法到子组件链
需要把上下文里的setCustomer方法逐层传递到负责编辑的NewContactModal组件:
修改Sale_resume.jsx
const { sale, selectedItems, setTotals, setCustomer } = useContext(SaleContext) <ContactInfoModal client={sale.customer} show={showContactInfoModal} handleClose={handleCloseContactInfoModal} setCustomer={setCustomer} // 新增:传递更新客户的方法 />
修改ContactInfoModal.jsx
const ContactInfoModal = ({ client, show, handleClose, refreshContactList, setCustomer }) => { // 新增接收setCustomer // ... <NewContactModal contact={client} show={updateContactModalShow} handleClose={handleCloseUpdateContactModal} setCustomer={setCustomer} // 传递给编辑组件 /> // ... }
2. 编辑成功后同步更新上下文状态
在NewContactModal的提交方法中,API返回成功后,用更新后的客户数据调用setCustomer,触发父组件重新渲染:
修改NewContactModal.jsx
const NewContactModal = ({ show, handleClose, contact, getContacts, setCustomer }) => { // 新增接收setCustomer const handleSubmit = async () => { // ... let response = {} let updatedContact = null if (contact) { response = await gestupApi.putContact(contact.id, { name, federalTaxId, address, neighborhood, number, zip, complement, selectedState, selectedCity, phoneNumber, email, suframa, stateTax, cityTax, contributorType, channel, birthDate }) // 假设API返回的更新后客户数据在response.data中 updatedContact = response.data } else { response = await gestupApi.postContact({ name, federalTaxId, address, neighborhood, number, zip, complement, selectedState, selectedCity, phoneNumber, email, suframa, stateTax, cityTax, contributorType, channel, birthDate }) updatedContact = response.data } if (response.code == 200) { resetStates() // 关键:如果是更新现有客户,同步到上下文状态 if (contact && setCustomer) { setCustomer(updatedContact) } getContacts ? getContacts() : "" contact ? toast.success("Contato atualizado com sucesso") : toast.success("Contato criado com sucesso") } else { contact ? toast.error("Falha ao atualizar o contato") : toast.error("Falha ao criar o contato") } handleClose() } // ... }
特殊情况处理
如果API更新后不返回完整客户数据,可在成功后重新获取该客户的最新数据再更新上下文:
// 在handleSubmit的成功分支替换同步逻辑 if (contact && setCustomer) { const fetchRes = await gestupApi.getContact(contact.id) if (fetchRes.code === 200) { setCustomer(fetchRes.data) } }
内容的提问来源于stack exchange,提问作者Wallace Nascimento
相关产品推荐
相关产品推荐

