反应:删除后更新状态

时间:2020-07-22 23:06:59

标签: reactjs axios

我正在尝试在删除后更新元素,而不刷新页面。当前,如果删除一条记录,则需要刷新页面才能看到结果。据我了解,需要更新useState,但我不知道该怎么做。如果我循环useEffect会起作用,但速度很慢,但是我认为循环get响应不是最好的主意。

  1. 从数据库中获取所有记录。
const PostsGetUtill = () => {
    const [posts, setPosts] = useState([]);

    const fetchPosts = () => {
        axios.get("api/v1.0/post/get").then(response => {
            console.log(response.data);
            setPosts(response.data);
        }).catch(function (error) {
            if (error.response) {
                console.log(error.response.data);
                console.log(error.response.status);
                console.log(error.response.headers);
            } else if (error.request) {
                console.log(error.request);
            } else {
                console.log('Error', error.message);
            }
            console.log(error.config);
        });
    };

    useEffect(() => {
        fetchPosts();
    }, []);           //  }, [fetchPosts]); <--- working well with loop 

    return (
        <section className="container-post">
            <PostMansonry posts={posts} columns={3} />
        </section>
    );
};

export default PostsGetUtill;
  1. 排序和映射记录
export default function PostMansonry({ posts, columns }) {
    return (
        <section className="masonry" style={{ gridTemplateColumns: `repeat(${columns}, minmax(275px, 1fr))` }}>
            {posts.sort((a, b) => a.zonedDateTime < b.zonedDateTime ? 1 : -1).map((posts, index) =>
                <MasonryPost {...{ posts, index, key: index }} />)
            }
        </section>
    )

}
  1. 将数据放入卡
export default function MasonryPost({ posts, index }) {
    return (
        <div key={index} className="masonry-post">
            <div className="card">
                <div className="card-body">
                    <h5 className="card-title">{posts.title}</h5>
                    <p className="card-text">{posts.description}</p>
                    <p className="card-text"><small className="text-muted"> {posts.zonedDateTime}</small></p>
                    <div><button type="button" onClick={(e) => PostsDeleteUtill(posts.post_Id)} className="btn btn-danger">Delete</button></div>
                </div>
            </div>
        </div>
    )
}

  1. 删除
const PostsDeleteUtill = async (post_Id) => {
    axios.delete(`api/v1.0/post/delete/${post_Id}`).then(response => {
        console.log(response);
    }).catch((error) => {
        if (error.response) {
            console.log(error.response.data);
            console.log(error.response.status);
            console.log(error.response.headers);
        } else if (error.request) {
            console.log(error.request);
        } else {
            console.log('Error', error.message);
        }
        console.log('error config', error.config);
    });
};

export default PostsDeleteUtill;

1 个答案:

答案 0 :(得分:1)

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

为此,您有2个选择:

  1. 使用全局状态(React Context,Redux等)
  2. 将您的PostsGetUtill句柄一直传递到setPosts

我认为选项1对于您的特定情况更干净一些,但是如果您在项目中的其他任何地方都不需要全局状态,那么也许可以使用一个不太干净的解决方案而不是实现整个全局状态结构仅一件事。

选项1伪代码:

您的PostsDeleteUtill组件将使用全局状态而不是本地状态:

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; 函数中:

PostsDeleteUtill

选项2伪代码:

在您的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; 组件中,创建并传递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> ); 中,再次传递您的PostMansonry

handleRemovePost

再次进入您的export default function PostMansonry({ posts, columns, handleRemovePost }) { return ( // Your existing code ... <MasonryPost {...{ posts, index, key: index, handleRemovePost }} />) ) }

MasonryPost

最后:

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:请注意,我只是添加了一个伪代码作为参考,试图指出需要更新的代码的特定部分。如果您需要有关全局状态的更多信息,可以检查React ContextRedux