【发布时间】: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