React lodash删除不工作

时间:2017-10-30 00:39:38

标签: javascript reactjs lodash

我有一个包含对象的state。我还有一个删除api,它基于stateobject property中删除对象。这是代码:

deleteItem(item_to_delete){
    const del_item = _.find(this.state.bucket_list, bucklistitem => bucklistitem.name === item_to_delete);
    fetch(url(this.props.api) + '/' + del_item._id, {
        method: "DELETE",
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
    });

    _.remove(this.state.bucket_list, bucketlistitem => bucketlistitem.name === item_to_delete);
    this.setState({ bucket_list: this.state.bucket_list });
}

但我知道我现在将state视为可变的,这是不好的。因此,我想通过创建state的副本,更改副本和setState来更改我的代码。这是代码:

deleteItem(item_to_delete){
    let bucket_list_copy = Object.assign({}, this.state.bucket_list); //Copy of state
    const del_item = _.find(bucket_list_copy, bucklistitem => bucklistitem.name === item_to_delete);
    fetch(url(this.props.api) + '/' + del_item._id, {
        method: "DELETE",
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
    });

    _.remove(bucket_list_copy, { name: item_to_delete });
    this.setState({ bucket_list: bucket_list_copy });
}

但是,虽然这会从数据库中删除该对象,但它不会从copied list中删除它。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

更改此行

_.remove(bucket_list_copy, {name: item_to_delete});

到这个

_.remove(bucket_list_copy, bucketlistitem => bucketlistitem.name === item_to_delete);

如果查看Lodash documentation,则删除不接受对象作为第二个参数。

答案 1 :(得分:0)

您可以使用拼接跳过几个步骤

const delItemIndex = _.findIndex(this.state.bucket_list, bucklistitem => bucklistitem.name === item_to_delete);
let newBucketList = this.state.bucket_list.splice(delItemIndex, 1);

fetch(url(this.props.api) + '/' + this.state.bucket_list[delItemIndex]._id, {
    method: "DELETE",
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    },
});

this.setState({ bucket_list: newBucketList  });