1

我正在尝试使用使用库制作的 API 并在 GraphQL 订阅的帮助下实时Apollo GraphQL更新组件。对于删除操作,我收到错误。这是来自试图从订阅更新数据的反应组件的代码。reactsubscriptions-transport-wsTypeError: Cannot add/remove sealed array elements

   componentWillReceiveProps(nextProps) {
        if (!this.subscription && !nextProps.data.loading) {
                let { subscribeToMore } = this.props.data
                this.subscription = [subscribeToMore(
                {
                    document: postDeleted,
                    updateQuery: (previousResult, { subscriptionData }) => {
                     const delPost = subscriptionData.data.postDeleted;
                     const mainData = previousResult.Posts;               

                     let post = mainData.find(post => post.id == delPost.id);
                     let updatedList =  mainData.splice(post, 1);
                     return updatedList;
                    },
                }
                )]
       }
    }
4

2 回答 2

5

mainData很可能是“密封的”,因此您的splice操作会引发错误:

let updatedList =  mainData.splice(post, 1);

解决方案是制作数组的副本(在此处使用数组解构):

let updatedList = [...mainData].splice(post, 1);

您可以像这样在 Chrome 控制台中尝试一下:

a = [1, 2, 3];
Object.seal(a);
a.splice(1)

// Uncaught TypeError: Cannot add/remove sealed array elements
//  at Array.splice (<anonymous>)
//  at <anonymous>:1:3

[...a].splice(1)

// [2, 3]
于 2018-01-30T06:36:40.403 回答
1

如果您的阵列已被密封,您可以复制一份并过滤掉您不想要的,如下所示:

let updatedList = mainData.filter(post => post.id !== delPost.id);

于 2018-03-27T13:11:28.193 回答