问题描述
我正在获取一个查询,并在拖动端使用 cache.modify 修改其中列表的顺序。 这确实会修改缓存,但这样做需要几毫秒。
如何重现问题: 我正在使用 react beautiful dnd 来制作拖放卡。 它提供了 onDragEnd 处理程序,我们可以在其中指定当用户停止拖动时会发生什么。 在这种情况下,我想对拖动端的列表重新排序。
缓存修改:
cache.modify({
id: cache.identify(data.pod),fields: {
stories(existingStoriesRefs,{ readField }) {
return reorder(existingStoriesRefs,sourceIndex,destinationIndex);
},},});
重新排序逻辑:
const reorder = (list: any[],startIndex: number,endindex: number) => {
const result = Array.from(list);
const [removed] = result.splice(startIndex,1);
result.splice(endindex,removed);
return result;
};
这在 setState 中使用故事正确工作和渲染。 但是,与其将 Apollo 数据复制到新的状态,我认为最好直接修改缓存。
但是,使用 cache.modify 是可行的,但是渲染有点小问题。看起来,它首先呈现现有列表,然后在下一次呈现中修改缓存。故障大约不到一秒,但对用户可见。
解决方法
我使用 cache.modify 内部、变异和乐观更新修复了它。
moveStoryMutation({
variables: {
id: stories[sourceIndex].id,sourceIndex,destinationIndex,},optimisticResponse: {
__typename: "Mutation",moveStory: true,update: (proxy) => {
proxy.modify({
id: proxy.identify(pod),fields: {
stories(existingStoryRefs) {
return reorder(
existingStoryRefs,destinationIndex
);
},});