【问题标题】:React/Redux: Why blog app is not removing the items?React/Redux:为什么博客应用程序不删除项目?
【发布时间】:2020-12-31 10:04:20
【问题描述】:

我使用 react 和 redux 创建了一个简单的博客应用程序,现在应用程序中只有两个功能 -> 渲染和删除博客。渲染工作正常,但不是删除。

问题很可能出在我的应用程序的减速器中。请建议。 这是我的全部代码。

沙盒链接:https://codesandbox.io/s/testing-75tjd?file=/src/index.js

动作

import { DELETE_BLOGS, GET_BLOGS } from "./actionTypes";

// for rendering list of blogs
export const getBlog = () => {
  return {
    type: GET_BLOGS,
  };
};

// for deleting the blogs
export const deleteBlogs = (id) => {
  return {
    type: DELETE_BLOGS,
    id,
  };
};

减速器

import { DELETE_BLOGS, GET_BLOGS } from "../actions/actionTypes";

const initialState = {
  blogs: [
    { id: 1, title: "First Blog", content: "A new blog" },
    { id: 2, title: "Second Blog", content: "Just another Blog" },
  ],
};

const blogReducer = (state = initialState, action) => {
  switch (action.types) {
    case GET_BLOGS:
      return {
        ...state, // a copy of state
      };
    case DELETE_BLOGS:
      return {
        ...state,
        blogs: state.filter((blog) => blog.id !== action.id),
      };
    default:
      return state; // original state
  }
};

export default blogReducer;

组件

import React, { Component } from "react";
import { connect } from "react-redux";
import { deleteBlogs } from "../actions/blogActions";

class AllBlogs extends Component {
  removeBlogs = (id) => {
    console.log("removeBlogs function is running with id", id);
    this.props.deleteBlogs(id); // delete action
  };

  render() {
    return (
      <div>
        {this.props.blogs.map((blog) => (
          <div key={blog.id}>
            <h3>{blog.title}</h3>
            <p>{blog.content}</p>
            <button onClick={() => this.removeBlogs(blog.id)}>delete</button>
            <hr />
          </div>
        ))}
      </div>
    );
  }
}

const mapStateToProps = (state) => ({
  blogs: state.blogs,
});

export default connect(mapStateToProps, { deleteBlogs })(AllBlogs);

【问题讨论】:

  • 你已经完成了 state.filter,而不是 state.blogs.filter

标签: reactjs redux


【解决方案1】:

问题

您在 reducer 中发送操作键 type 并以 action.types 接收

解决方案

const blogReducer = (state = initialState, action) => {
  switch (action.type) { // change `types` to `type`
    case DELETE_BLOGS:
      return {
        ...state,
        blogs: state.blogs.filter((blog) => blog.id !== action.id)
      };
    default:
      return state; // original state
  }
};
 

【讨论】:

猜你喜欢
  • 2019-11-02
  • 1970-01-01
  • 1970-01-01
  • 2016-04-01
  • 2020-08-18
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 1970-01-01
相关资源
最近更新 更多