【问题标题】:Deleting post with React Redux api delete request使用 React Redux api 删除请求删除帖子
【发布时间】:2020-05-31 17:36:44
【问题描述】:

当我在控制台记录 this.props 时,我得到一个带有 post.id 的数组,我想使用 onClick 函数从列表中删除该项目并且不在页面上显示 我的代码有什么问题?

这就是我所拥有的

export const deletePost = id => dispatch => {
  fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
    method: "DELETE"
  })
    .then(res => res.json())
    .then(post =>
      dispatch({
        type: DELETE_POST,
        payload: id
      }),
    );
};

my reducer:

const initialState = {
  items: [],
  item: {}
};
    case FETCH_POSTS:
      return {
        ...state,
        items: action.payload
      };
    case DELETE_POST:
      return {
        ...state,
        items: action.payload
      };

Component contains of

const mapStateToProps = state => ({
  posts: state.postsReducer.items,
});

const mapDispatchToProps = {
  fetchPosts, deletePost
}

And Delete button on each post:

<button key={post.id} onClick={()=>this.props.deletePost()}>X</button>```

【问题讨论】:

    标签: reactjs api redux fetch thunk


    【解决方案1】:

    我在这里看到了一些你应该看看的东西,希望它们能帮助你解决问题。

    首先,请注意,您的 deletePost 函数需要一个带有帖子 ID 的参数。但是,在您为按钮发布的 JSX 代码中,您根本没有向函数传递任何值。这意味着在分派操作时属性payload 将具有undefined 值。

    确保您更新您的视图以传递一个 id,因此您调用正确的端点(您的 DELETE 请求现在可能指向 https://jsonplaceholder.typicode.com/posts/undefined)并且减速器实际上接收到您想要的帖子的 id删除:

    <button key={post.id} onClick={()=>this.props.deletePost(post.id)}>X</button>
    

    您必须检查的第二件事是减速器的实现。根据我在您的消息和deletePost 方法的代码中的理解,action.payload 应该包含一个数字。

    既然如此,你的 reducer 如何处理 reducer 中的 DELETE_POST 动作对我来说意义不大。

    case DELETE_POST:
        return {
            ...state,
            items: action.payload
        };
    

    Reducer 应该是纯函数,对于给定的状态和动作,它会根据接收到的动作返回一个全新的状态。还要记住,您收到的状态根本无法更改:如果原始实例以任何方式发生变异,您的代码将无法工作。

    在这种情况下,您需要返回一个新状态,其中您的 items 属性被替换为您要删除的 id 缺失的新列表。然而,在您编写的这段代码中,您将items 数组替换为一个数字。这不是应该发生的事情,首先items 应该仍然是一个数字数组。

    您真正需要做的是创建一个不包含您要删除的项目的新数组。您可以使用filter 方法来实现:

    case DELETE_POST:
        return {
            ...state,
            items: state.items.filter(item => item !== action.payload)
        };
    

    这段代码应该完全符合您的要求:在这里,我们为您所在州的items 属性分配了一个全新的数组,其中不包括已删除的帖子。

    filter 返回一个数组,其中包含指定函数为其返回true 的项目。在这种情况下,我们传递给 filter 的箭头函数会针对与您要删除的帖子的 id 不同的每个项目返回 true

    通过使用此方法,您也不会遇到初始state.items 值以某种方式发生突变的问题,因为filter 返回Array 的新实例并且不会改变原始值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-05
      • 2018-12-24
      • 1970-01-01
      • 2019-01-20
      • 2018-04-10
      • 2016-06-11
      • 1970-01-01
      相关资源
      最近更新 更多