且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Apollo客户端写入查询未更新UI

更新时间:2022-12-16 23:29:54

如果查看文档示例,您会发现它们以不变的方式使用数据.传递给写查询的数据属性与读取的对象不同.突变此对象不太可能受到Apollo的支持,因为如果不进行深度拷贝和比较之前/之后的数据,该对象将无法非常有效地检测到您修改了哪些属性.

If you look at the documentation examples, you will see that they use the data in an immutable way. The data attribute passed to the write query is not the same object as the one that is read. Mutating this object is unlikely to be supported by Apollo because it would not be very efficient for it to detect which attributes you modified, without doing deep copies and comparisons of data before/after.

const query = gql`
  query MyTodoAppQuery {
    todos {
      id
      text
      completed
    }
  }
`;
const data = client.readQuery({ query });
const myNewTodo = {
  id: '6',
  text: 'Start using Apollo Client.',
  completed: false,
};
client.writeQuery({
  query,
  data: {
    todos: [...data.todos, myNewTodo],
  },
});

因此,您应该尝试使用相同的代码,而不会使数据发生变异.例如,您可以使用lodash/fp中的set来帮助您

So you should try the same code without mutating the data. You can use for example set of lodash/fp to help you

const data = client.readQuery({...});
const newData = set("cart.items["+itemIndex+"].quantity",newItemQuantity,data);
this.props.client.writeQuery({ ..., data: newData });

对于更复杂的突变,建议 ImmerJS

It recommend ImmerJS for more complex mutations