首页 > 解决方案 > 如何删除数组中的对象?

问题描述

我使用了 componentDidUpdate 并在其中放置了一个 shift 方法,该方法用于从 JSON 数组中删除一个对象,从而重新渲染显示的帖子,但 shift 方法从数组中独立删除第一个对象,其中删除按钮打开我会按这个帖子吗?那么,是否有可能绕过删除第一个元素而支持指定要删除的元素呢?

componentDidUpdate(prevProps, prevState) {
        const {posts} = this.props;
        const indexPosts = posts.findIndex((post) => post.id === this.state.postId);

        if(prevProps.posts !== posts){
            this.handleData();
        } else if (indexPosts !== -1)
        {
            this.informationAlert();
            const log = posts.splice(indexPosts, 1);
            console.log(log);
        }   
    }

编辑:行动

export const deletedPost = (id) => (dispatch) => {
    axios
        .delete(`https://jsonplaceholder.typicode.com/posts/${id}`, id, {
            headers: {
                'Content-type': 'application/json'
            }
        })
        .then((post) =>
            dispatch({
                type: DELETED_POST,
                payload: post.data
            })
        )
        .catch((err) => console.log(err));
};
import { FETCH_POSTS, NEW_POST, DELETED_POST, FETCH_COMMENTS, NEW_COMMENT } from '../actions/types';

const initialState = {
    items: [],
    item: {},
    itemComent: [],
    itemNewComment: {},
    deletedPost: []
};

export default function (state = initialState, action) {
    switch (action.type) {
        case FETCH_POSTS:
            return {
                ...state,
                items: action.payload
            };
        case NEW_POST:
            return {
                ...state,
                item: action.payload
            };
        case DELETED_POST:
            return {
                ...state,
                deletedPost: action.payload
            };
        case FETCH_COMMENTS:
            return {
                ...state,
                itemComent: action.payload
            }
        case NEW_COMMENT:
            return {
                ...state,
                itemNewComment: action.payload
            }
        default:
            return state;
    }
}

编辑2:

const mapStateToProps = (state) => ({
    posts: state.posts.items,
    newPost: state.posts.item,
    deletedPost2: state.posts.deletedPost
});

编辑 3:

handleDeletedPost = (id) => {
        this.setState({
            postId: id
        })
    }

编辑4:

//I added in constructor 
this.state: dataPost: '',

//next I create function to load data and send to state dataPost
handleData = (e) => {
        const {posts} = this.props;
        const {dataPost} = this.state;
        const letang = posts;
        const postsData = dataPost;

        if (postsData.length <= 0) {            
            this.setState({
                dataPost: letang
            })
        } else {
            console.log('stop')
        }       
    }
// next i create in componentDidUpdate this code
componentDidUpdate(prevProps, prevState) {
        const {posts} = this.props;
        const indexPosts = posts.findIndex((post) => post.id === this.state.postId);

        if(prevProps.posts !== posts){
            this.handleData();
        } else if (indexPosts !== -1)
        {
            this.informationAlert();
            const log = posts.splice(indexPosts, 1);
            console.log(log);
        }   
    }

** 当我添加循环 if (indexPosts !== -1) 时,我的数组只被剪切一个对象:-) API 帖子:https ://jsonplaceholder.typicode.com/posts/

当您按详细信息然后按删除图标时,结果会在此链接上可见:https ://scherlock90.github.io/api-post-task/

标签: jsonreactjsredux

解决方案


您需要使用splice从数组中删除一个元素。在 splice 中,您需要在第二个参数中提供 startIndex 和要删除的元素数。在下面的代码中使用findIndex方法查找索引,第二个参数是 1,因为我们只需要删除 1 个元素。

尝试这个

componentDidUpdate (prevProps, prevState) {
        if (prevProps.deletedPost) {
            const { posts } = this.props
            const letang = posts.splice(posts.findIndex( (post)=> post.id === prevProps.deletedPost.id), 1);

           console.log(posts); // this should have array without deletedPost
        }
    }

推荐阅读