import { Link, useNavigate } from "react-router-dom";
import { useBlogContext } from '../Hooks/useBlogContext';
const Blogs = ({ blog }) => {
const navigate = useNavigate();
const { dispatch } = useBlogContext();
const handleClick = async (id) => {
try {
const response = await fetch(`/api/blog/${id}`, {
method: 'DELETE',
});
const json = await response.json();
if (response.ok) {
dispatch({ type: 'DELETE_BLOG', payload: json });
} else {
console.error('Failed to delete blog:', json);
}
} catch (error) {
console.error('Error while deleting blog:', error);
}
};
return (
<div className="blogs-container">
{blog && blog.map(blogs => (
<div key={blogs._id} className="Home-blogs">
<div className="Blog-img-container">
<img src={blogs.img_url} alt="Blog" className="Blog-img" />
</div>
<Link to={`/blogs/${blogs._id}`}>
<h2 className="Blog-title">{blogs.title}</h2>
<h3 className="Blog-author">{blogs.author}</h3>
<p className="Blog-content">{blogs.content}</p>
<p>{blogs.createdAt}</p>
</Link>
<div className="blog-icons">
<span className="material-symbols-outlined" onClick={() => handleClick(blogs._id)}>Delete</span>
<span className="material-symbols-outlined" onClick={() => navigate(`/blogs/update/${blogs._id}`)}>Edit</span>
</div>
</div>
))}
</div>
);
};
export default Blogs;
博客道具来自:
import { useEffect, useState } from "react";
import Blogs from "../components/Blogs";
import { useBlogContext } from "../Hooks/useBlogContext";
const Home = () => {
const [blogs, setBlogs] = useState(null);
const { dispatch } = useBlogContext();
useEffect(() => {
const fetchBlog = async () => {
const response = await fetch('/api/blog', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
});
const json = await response.json();
if (response.ok) {
setBlogs(json);
dispatch({ type: 'SET_BLOGS', payload: json });
}
};
fetchBlog();
}, [dispatch]);
return (
<div className="Home">
<div className="Home-container">
<h1>RetroBlog</h1>
<p>Where you can create, update, and show ideas</p>
</div>
<h1>All Recent Blogs</h1>
<Blogs blog={blogs} />
</div>
);
};
export default Home;
这是我的删除博客代码,并且有调度,但没有正常工作
import { createContext, useReducer } from 'react';
// Create BlogContext
export const BlogContext = createContext();
// BlogReducer to handle actions
export const BlogsReducer = (state, action) => {
switch (action.type) {
case 'SET_BLOGS':
return {
blogs: action.payload
};
case 'CREATE_BLOG':
return {
blogs: [action.payload, ...state.blogs]
};
case 'DELETE_BLOG':
return {
blogs: state.blogs.filter((b) => b._id !== action.payload._id)
};
case 'UPDATE_BLOG':
return {
blogs: state.blogs.map((b) =>
b._id === action.payload._id ? action.payload : b
)
};
default:
return state;
}
};
// BlogContextProvider component
export const BlogContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(BlogsReducer, {
blogs: null
});
return (
<BlogContext.Provider value={{ ...state, dispatch }}>
{children}
</BlogContext.Provider>
);
};
这是我的上下文代码 当在前端我单击删除图标
该项目的完整代码: https://github.com/ArunM037/Retro_Blog-Using-Mern-Stack
我希望当我单击删除按钮时上下文能够正常工作
您正在 BlogContext
...
中复制您的博客 状态
const [state, dispatch] = useReducer(BlogsReducer, { blogs: null });
和
Home
组件...
const [blogs, setBlogs] = useState(null);
这些是完全独立的对象。对其中一个进行更改不会影响另一个。
最简单的解决方案是仅使用您的上下文状态。
从
Home
中删除本地状态并使用
const { blogs, dispatch } = useBlogContext();
您甚至可以在
Blogs
组件中执行相同的操作,因此无需传递 blog
属性。
您正在 BlogContext
...
中复制您的博客 状态
const [state, dispatch] = useReducer(BlogsReducer, { blogs: null });
和
Home
组件...
const [blogs, setBlogs] = useState(null);
这些是完全独立的对象。对其中一个进行更改不会影响另一个。
最简单的解决方案是仅使用您的上下文状态。
从
Home
中删除本地状态并使用
const { blogs, dispatch } = useBlogContext();
您甚至可以在
Blogs
组件中执行相同的操作,因此无需传递 blog
属性。