使用 Apollo 的突变组件时,有没有办法从更新回调函数内部获取突变的变量?
<Mutation
mutation={mutation}
update={(cache, result) => {
// is there any way to get the mutation variables here?
}}
>
{mutate => <MyComponent onSubmit={mutate} />}
</Mutation>
不幸的是,该信息不会传递给更新函数。您需要将Mutation
组件移动到MyComponent
(或将状态向上和移出MyComponent
(,以便您可以将变量直接传递给Mutation
组件,而不是mutate
函数:
<Mutation
mutation={mutation}
variables={{ ... }}
update={()=> {
// Now whatever values you used for the mutation will also be available here
}}
>
{mutate => {
// mutate can be used without passing any variables to it
}}
</Mutation>
你可能有一个独特的用例,但通常我们不需要首先担心变量。通常,插入、删除和更新突变会返回插入/删除/更新的对象,并且该有效负载足以更新缓存。如果您的突变没有返回突变的数据,并且您有能力更改 API,则可以考虑这样做,因为这也会有所帮助。