【问题标题】:How to delete object in array?如何删除数组中的对象?
【发布时间】:2019-06-05 15:52:29
【问题描述】:

我使用了 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/

【问题讨论】:

  • 你也不应该像那样改变道具。创建一个状态来保存你的变异数组。
  • 请发布您的示例数组以及deletedPost.中的内容
  • @Chase 为什么这是变异数据的错误方法?
  • 我添加的第一个帖子可能是您要求的信息。 @kiranvj

标签: json reactjs redux


【解决方案1】:

您需要使用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
        }
    }

【讨论】:

  • 解释他们介绍的代码的答案比那些不解释的更有用......
  • @kiranvj 您的提案导致表格为空,但没有删除任何帖子
  • @Sen console.log(posts); // 这应该有没有deletedPost的数组
  • 是的,有空数组
  • 但是我改成 const letang = this.props.posts.slice(this.props.posts.findIndex( (post)=> post.id === this.state.postId), 1 );然后我在控制台日志中看到第一个帖子
【解决方案2】:

这可能会有所帮助:

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

slice() 获取对象的索引和要删除的可选项目数。因为您只想删除一个传递 1 的对象。

【讨论】:

  • 我尝试了一个有条不紊的拼接,但它仍然会删除数组中的第一个元素而不是选定的元素
  • deletePost 是对象还是id
【解决方案3】:

这可能会有所帮助,请尝试过滤掉数组中不需要的对象。

componentDidUpdate (prevProps, prevState) {
    if (prevProps.deletedPost) {
        const letang = this.props.items.filter(p => p.id !== prevProps.deletedPost.id);
    }
}

更新 我认为您应该删除 redux 商店中的项目,而不是尝试从您的 api 中删除帖子,因为 api 可能宁愿随机生成相同的数据。将您的 actionCreator 更改为

export const deletedPost = (id) => {
   dispatch({
       type: DELETED_POST, 
       payload: id 
   });
};

然后在你的 reducer 中使用它,这样你就可以专注于来自你的 reducer 存储的 items 数组。然后从减速器中删除deletedPost: []

...
    case DELETED_POST:
        const newItems = state.items.filter(p => p.id !== action.payload);
        return {
            ...state,
            items: [ ...newItems ],
        };
...

【讨论】:

  • @SeN 来自您的 reducer,您使用的是项目而不是帖子,请尝试将 this.props.posts.filter 替换为 this.props.items.filter
  • 但是如果你看到 EDIT 2 那么你就会明白为什么是帖子
  • @SeN 好的。现在我看到你在你的mapStateToProps 中使用deletedPost2。将 prevProps.deletedPost.id 更改为 prevProps.deletedPost2.id
  • 然后我看到错误:“Uncaught TypeError: Cannot read property 'filter' of undefined at Posts.componentDidUpdate”
  • 在控制台日志中,我看到一个帖子总是被选中的感觉发生了变化,但不幸的是,它不会呈现应用程序中显示的对象中的状态。而且消失的总是一个元素,而不是被选中的帖子一个一个减去
【解决方案4】:

使用splice()删除:),你可以找到要删除的帖子的索引,然后用这个方法删除它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-16
    • 2017-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    相关资源
    最近更新 更多