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

React如何无需页面刷新,展示新增至MongoDB的Recipe数据?

问题:如何无需页面刷新,在页面的<div className="all-recipes-list"></div>中展示新增的Recipe?

现有代码的核心问题:

  • 加载recipes时,循环调用setRecipes会导致最终只保留最后一条数据(每次调用都基于初始空数组)
  • 提交表单时,未传递表单数据给API,也未在成功后更新本地状态

修复步骤:

1. 修复recipes加载逻辑

直接将API返回的完整数组赋值给状态,无需循环逐个添加:

const loadAllRecipes = () => {
  axios({
    method: 'GET',
    url: `${process.env.REACT_APP_API}/recipe`,
  })
  .then(response => {
    // 直接设置完整的recipes数组
    setRecipes(response.data.message);
  })
  .catch(error => {
    // 处理错误
  });
};

2. 完善表单提交逻辑

  • 传递表单数据给POST API
  • 成功后将新增的Recipe添加到本地状态(用函数式更新避免闭包问题)
  • 清空表单输入(优化用户体验)
const handleSubmit = event => {
  event.preventDefault();

  axios({
    method: 'POST',
    url: `${process.env.REACT_APP_API}/recipe`,
    // 传递表单数据给后端
    data: { recipe_name, image_url }
  })
  .then(response => {
    console.log('Recipe is saved successfully!', response);
    // 假设API返回了新增的recipe对象,用函数式更新添加到数组末尾
    setRecipes(prevRecipes => [...prevRecipes, response.data.message]);
    // 清空表单输入
    setFormFieldValues({
      recipe_name: '',
      image_url: '',
      buttonText: 'Submit'
    });
  })
  .catch(error => {
    // 处理错误
  });
};

3. (可选)优化状态更新逻辑

为避免闭包陷阱,所有状态更新推荐使用函数式写法,比如修改handleChange:

const handleChange = (name) => (event) => {
  setFormFieldValues(prevState => ({...prevState, [name]: event.target.value}));
};

修改完成后,提交表单时新的Recipe会立即被添加到页面列表中,无需刷新页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 14:32:44