ReactJS:TypeError:无法添加/删除密封的数组元素

时间:2018-01-23 15:21:20

标签: javascript reactjs graphql graphql-subscriptions

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

   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;
                    },
                }
                )]
       }
    }

2 个答案:

答案 0 :(得分:5)

mainData很可能是“sealed”,因此您的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]

答案 1 :(得分:1)

如果您的阵列已被密封,您可以复制它并过滤掉您不想要的那个:

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