Reactjs 反应:删除后更新状态

Reactjs 反应:删除后更新状态,reactjs,axios,Reactjs,Axios,我试图在删除后更新元素,而不刷新页面。当前,如果删除记录,则需要刷新页面以查看结果。据我所知,需要更新useState,但我不知道怎么做。如果我循环useffect,效果会很慢,但我认为循环get响应不是最好的方法 从数据库中获取所有记录 基本上,您需要做的是,在PostsDeleteUtill函数中,在axios.delete的承诺返回中,您需要更新posts状态,该状态在PostsGetUtill中设置 为此,您有两个选项: 使用全局状态(反应上下文、Redux等) 将你的setPosts句

我试图在删除后更新元素,而不刷新页面。当前,如果删除记录,则需要刷新页面以查看结果。据我所知,需要更新
useState
,但我不知道怎么做。如果我循环
useffect
,效果会很慢,但我认为循环
get
响应不是最好的方法

  • 从数据库中获取所有记录

  • 基本上,您需要做的是,在
    PostsDeleteUtill
    函数中,在
    axios.delete
    的承诺返回中,您需要更新
    posts
    状态,该状态在
    PostsGetUtill
    中设置

    为此,您有两个选项:

  • 使用全局状态(反应上下文、Redux等)
  • 将你的
    setPosts
    句柄一直传递到你的
    PostsDeleteUtill
  • 我认为选项1对于您的具体情况来说更干净一些,但是如果您在项目的其他任何地方都不需要全局状态,那么使用一个不那么干净的解决方案,而不是只为一件事实现整个全局状态结构,可能是好的

    选项1伪代码: 您的
    PostsGetUtill
    组件将使用全局状态而不是本地状态:

    const PostsGetUtill = () => {
        // Remove this:
        // const [posts, setPosts] = useState([]);
    
        const fetchPosts = () => {
            axios.get("api/v1.0/post/get").then(response => {
                console.log(response.data);
                // Instead of a local "setPosts" you would have a global
                // "setPosts" (in Redux, this would be a dispatch)
                dispatch({type: "PUT_POSTS", action: response.data})
            }).catch(function (error) {
                // No changes here...
            });
        };
    
        // This runs only the first time you load this component
        useEffect(() => {
            fetchPosts();
        }, []); 
    
        // Use your global state here as well:
        return (
            <section className="container-post">
                <PostMansonry posts={globalState.posts} columns={3} />
            </section>
        );
    };
    
    export default PostsGetUtill;
    

    选项2伪代码: 在
    PostsGetUtill
    组件中,创建并传递
    handleRemovePost

    // Your existing code ...
    const handleRemovePost = (postID) => {
        const filteredPosts = posts.filter(post => post.id !=== postID)
        setPosts(filteredPosts)
    }
    
    return (
        <section className="container-post">
            <PostMansonry posts={posts} columns={3} handleRemovePost={handleRemovePost} />
        </section>
    );
    
    再次在您的
    MasonryPost

    export default function PostMansonry({ posts, columns, handleRemovePost }) {
        return (
            // Your existing code ...
            <MasonryPost {...{ posts, index, key: index, handleRemovePost }} />)
        )
    }
    
    export default function MasonryPost({ posts, index, handleRemovePost }) {
        return (
            // Your existing code ...
            <button type="button" onClick={(e) => PostsDeleteUtill(posts.post_Id, handleRemovePost)} className="btn btn-danger">Delete</button>
        )
    }
    


    PS:请注意,我只是添加了一个伪代码作为参考,试图指出代码中需要更新的特定部分。如果您需要有关全局状态的更多信息,您可以检查并

    最好使用一些状态管理库,如Redux,因为
    delete
    组件太深,您无法传递那么深的delete函数(技术上可以,但不是很方便)。因此,制作全局prop
    posts
    ,并使用
    dispatch
    delete
    组件获取新帖子。
    const PostsGetUtill = () => {
        // Remove this:
        // const [posts, setPosts] = useState([]);
    
        const fetchPosts = () => {
            axios.get("api/v1.0/post/get").then(response => {
                console.log(response.data);
                // Instead of a local "setPosts" you would have a global
                // "setPosts" (in Redux, this would be a dispatch)
                dispatch({type: "PUT_POSTS", action: response.data})
            }).catch(function (error) {
                // No changes here...
            });
        };
    
        // This runs only the first time you load this component
        useEffect(() => {
            fetchPosts();
        }, []); 
    
        // Use your global state here as well:
        return (
            <section className="container-post">
                <PostMansonry posts={globalState.posts} columns={3} />
            </section>
        );
    };
    
    export default PostsGetUtill;
    
    const PostsDeleteUtill = async (post_Id) => {
        axios.delete(`api/v1.0/post/delete/${post_Id}`).then(response => {
            // Update global state here. Probably filter the data to remove
            // the deleted record
            const updatedPosts = globalState.posts.filter(post => post.id !== response.data.id)
        }).catch((error) => {
          // No changes here
        });
    };
    
    export default PostsDeleteUtill;
    
    // Your existing code ...
    const handleRemovePost = (postID) => {
        const filteredPosts = posts.filter(post => post.id !=== postID)
        setPosts(filteredPosts)
    }
    
    return (
        <section className="container-post">
            <PostMansonry posts={posts} columns={3} handleRemovePost={handleRemovePost} />
        </section>
    );
    
    export default function PostMansonry({ posts, columns, handleRemovePost }) {
        return (
            // Your existing code ...
            <MasonryPost {...{ posts, index, key: index, handleRemovePost }} />)
        )
    }
    
    export default function MasonryPost({ posts, index, handleRemovePost }) {
        return (
            // Your existing code ...
            <button type="button" onClick={(e) => PostsDeleteUtill(posts.post_Id, handleRemovePost)} className="btn btn-danger">Delete</button>
        )
    }
    
    const PostsDeleteUtill = async (post_Id, handleRemovePost) => {
        axios.delete(`api/v1.0/post/delete/${post_Id}`).then(response => {
            handleRemovePost(response);
        })
    };