Amplify执行mutation时如何保持列表顺序 避免更新项移至列表末尾
列表更新保留原有排序的解决方法
问题原因
你当前实现中更新后的条目移动到列表末尾,是因为代码逻辑先通过filter移除了对应id的旧条目,再将更新后的条目直接追加到过滤后的数组末尾,自然丢失了原有的排序位置。
解决方案
要保持原有列表顺序,只需匹配到对应id的条目后直接替换内容即可,无需调整其他条目的位置,推荐使用更简洁的map遍历实现:
this.updateProductListener = API.graphql( graphqlOperation(onUpdateProducts) ).subscribe({ next: productData => { console.log(productData); const newProduct = productData.value.data.onUpdateProducts; // 用map遍历保持原有顺序,仅替换匹配id的条目 const updatedProducts = this.state.products.map(product => product.id === newProduct.id ? newProduct : product ); this.setState({ products: updatedProducts }); this.updateProductListener.unsubscribe() } });
如果需要通过索引操作的方式实现,也可以用以下写法,效果完全一致:
const updateIndex = this.state.products.findIndex(product => product.id === newProduct.id); // 增加索引存在的判断,避免非法索引报错 if (updateIndex > -1) { const updatedProducts = [...this.state.products]; updatedProducts[updateIndex] = newProduct; this.setState({ products: updatedProducts }); }
内容的提问来源于stack exchange,提问作者user3697484
相关产品推荐
相关产品推荐

