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

提交博客数据后useSelector未返回最新值需手动刷新问题求助

问题根因与修复方案

你的问题由三处错误共同导致,按优先级修改即可:

1. 先修正addBlog action的异步逻辑错误

你目前的axios.post的then写法是同步执行alert,没有正确接收接口返回值,导致dispatch到reducer的payload是undefined,直接覆盖了store里的博客列表:

export const addBlog =
 (title, content, author, category) => async (dispatch) => {
   try {
    const result = await axios
    .post("http://localhost:3001/api/v1/blog", {
      blog_title: title,
      blog_content: content,
      author_id: author,
      category_id: category,
    })
    // 原写法会立即执行alert,没有接收接口返回值,这里修正
    .then((res) => {
      alert("博客添加成功")
      return res.data.data
    })
    .catch((err) => {
      alert(err)
      throw err
    });

    // 新增成功后主动拉取全量列表,保证数据和后端完全同步
    dispatch(blogList())

    dispatch({
      type: ADD_BLOG,
      payload: result,
    });
  } catch (err) {
    dispatch({
      payload: err,
    });
  }
};

2. 修正提交逻辑的跳转时机

你目前提交后直接跳转,没有等异步新增请求完成,跳回首页时store还没更新:

// 提交函数改成async,等待dispatch异步执行完成再跳转
const submitHandler = async (e) => {
  e.preventDefault();
  await dispatch(addBlog(title, content, author, category));
  setTitle("");
  setContent("");
  setCategory("");
  history.push("/Home");
};

可选优化:调整ADD_BLOG reducer逻辑(如果不想每次新增都拉全量列表)

如果你的新增接口返回的是完整的单条博客数据,可以直接在本地合并列表,减少一次接口请求:

case ADD_BLOG:
  return {
    ...state,
    // 不要直接覆盖整个列表,把新增项拼到现有数组末尾
    blog: [...state.blog, action.payload],
 };

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:15:01