You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目中Firestore物料列表添加后无法刷新的问题排查

问题排查与修复

核心问题1:异步操作未等待,刷新时机过早

你的createNewMaterial方法中,materialService.updateCreateGlobalMaterial(newMaterial)是写入Firestore的异步操作,但你没有等待它完成就直接调用refreshList()——此时数据库还没完成新数据的持久化,pullMaterials拉取的自然还是旧数据。

修复代码:

修改AddMaterialModal中的createNewMaterial为异步函数,等待写入完成后再刷新:

const createNewMaterial = async () => {
  await materialService.updateCreateGlobalMaterial(newMaterial);
  if (refreshList != undefined) {
    refreshList();
    setOpenModal(false);
  }
};

核心问题2:Modal渲染条件错误

Materials页面中渲染Modal的条件用了{setOpenAddMaterialModal && (...)},setOpenAddMaterialModal是状态更新函数,在JS中会被判定为true,导致Modal始终挂载在DOM中(即使处于关闭状态)。虽然这不一定直接导致刷新失败,但会引发不必要的组件渲染问题,应改为使用状态值openAddMaterialModal:

修复代码:

{openAddMaterialModal && (
  <Modal
    open={openAddMaterialModal}
    close={() => {
      setOpenAddMaterialModal(false);
    }}
    title="Add Material"
    className=""
  >
    <AddMaterialModal
      editting={false}
      setOpenModal={setOpenAddMaterialModal}
      refreshList={pullMaterials}
    />
  </Modal>
)}

额外验证点:物料数据是否正确绑定

从代码注释//input some material data here.来看,需确认输入框的值是否正确绑定到newMaterial状态。如果输入内容没有更新newMaterial,提交的始终是初始占位数据,即使刷新也看不到预期的新物料。若未绑定,需要将const [newMaterial] = useState改为const [newMaterial, setNewMaterial] = useState,并在输入框的onChange事件中调用setNewMaterial更新状态。


内容的提问来源于stack exchange,提问作者Alula48

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 13:01:04