我尝试使用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;
},
}
)]
}
}
答案 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);