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

使用React/Redux创建文章时API刷新导致无法重复创建新文章

问题分析与解决方案

我一眼就看出问题的根源了——你每次回到首页(/)时会重新触发fetch_posts这个action,但JSONPlaceholder的POST接口是模拟实现,不会真正将你新建的文章保存到服务器。所以当重新获取帖子列表时,Redux的state会被接口返回的原始10条数据完全替换,之前添加的新文章自然就被覆盖消失了。

具体解决步骤

1. 修改Reducer,避免覆盖本地新增的文章

当前你的FETCH_POSTS分支是直接用接口返回数据替换整个state,我们需要调整逻辑,只在首次加载时替换state,后续保留已有的本地新增内容:

// Posts-reducer.js
import { FETCH_POSTS, ERROR_FETCH_POSTS, DELETE_FETCH_POSTS, CREATE_POST } from "../actions/actions-type"; 

export default (state = [], actions) => { 
  switch (actions.type) { 
    case FETCH_POSTS:
      // 如果state已有内容(说明之前加载过+添加了新文章),则保留现有数据,不覆盖
      return state.length > 0 ? state : actions.payload;
    case ERROR_FETCH_POSTS: 
      return actions.error; 
    case DELETE_FETCH_POSTS: 
      return state.filter(post => post.id !== actions.payload.id); 
    case CREATE_POST: 
      return [...state, actions.payload]; 
    default: 
      return state;
  }
};

如果希望同时保留原始数据和本地新增内容(并去重),也可以用这种写法:

case FETCH_POSTS:
  // 合并现有state与接口返回数据,通过id去重
  const combinedPosts = [...state, ...actions.payload];
  return Array.from(new Map(combinedPosts.map(post => [post.id, post])).values());

2. 控制首页的fetch触发时机

确保fetch_posts只在首页组件首次挂载时调用,而不是每次组件渲染(比如从创建页返回时)都执行:

  • 类组件写法:
componentDidMount() {
  this.props.fetch_posts();
}
  • 函数组件写法:
import { useEffect } from 'react';

useEffect(() => {
  props.fetch_posts();
}, []); // 空依赖数组确保只执行一次

3. 可选优化:标记本地新增的帖子

可以给本地创建的帖子添加一个标识,方便后续区分处理(比如删除逻辑):

// Action函数
export function create_post(post) {
  return dispatch => {
    axios
      .post("https://jsonplaceholder.typicode.com/posts/", { ...post })
      .then(res => dispatch({ 
        type: CREATE_POST, 
        payload: {...res.data, isLocal: true} // 添加本地标识
      }));
  };
}

补充说明

JSONPlaceholder作为模拟API,所有POST/PUT/DELETE请求都是“假动作”——它只会返回模拟响应,不会真的修改服务器端数据。所以每次调用GET接口获取帖子列表,拿到的都是初始的10条数据,这就是你之前新增的帖子会消失的核心原因。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:27:59