背景:始终能够使Apollo商店缓存更新,但没有UI
问题:
“反应”:“〜16.9.0”
“ @ apollo / react-hooks”:“ ^ 3.1.3”
UI和缓存更新的代码到我的项目中:
update: (store, { data: { newPhoto } }) => {
const { bookInfo } = store.readQuery({ query: GET_BOOK_BY_ID, variables: { bookId } });
bookInfo.photos = [...bookInfo.photos, newPhoto];
store.writeQuery({
query: GET_BOOK_BY_ID,
variables: { bookId },
data: {
bookInfo
}
});
}
在此行:bookInfo.photos = [...bookInfo.photos, newPhoto];
中,bookInfo对象被直接修改,并刚刚传递回writeQuery
的data
[这对我来说似乎不好,因为我看到人们说它必须是“不可变的”或“传递新对象”,等等。
如果您遇到相同的事情,请检查以下列表:
freezeResults
和assumeImmutableResults
应用于ApolloClient
,将有助于发现问题。就我而言,问题实际上是在父组件内部发生的,该组件使Apollo存储对象发生了突变,而不是调用client.writeQuery
的组件,我认为这通常也很难引起其他人的注意。 const client = new ApolloClient({
link: ...,
cache: new InMemoryCache({
freezeResults: true, // new
}),
assumeImmutableResults: true, // new
});
client
返回的useMutation
,然后您会得到client.writeQuery
进行更新。尽管我不确定这一点,但仍有很多人在传播此信息,在某些情况下可能会有所帮助。import { useMutation } from '@apollo/react-hooks';
import produce from "immer";
const [mutate, { client }] = useMutation(MUTATION_GQL);
const submit = () => {
mutate({
variables: { inputs },
update: (store, { data: { response }) => {
// get existing cache returned from the query
const cache = store.readQuery({ query: QUERY_GQL, variables: { id } });
// manipulate the cache in immutable fashion
const data = produce(cache, draftCache => {
draftCache.title = "new title";
draftCache.approval = response;
});
// write the cache back to that query
// REMEMBER the variables inside writeQuery too!
client.writeQuery({
query: QUERY_GQL,
variables: { id },
data,
});
}
})
}
useQuery
而不是ApolloClient
来读取readQuery
中的数据,所以您将从Apollo的存储中获取更新的缓存