如何阻止useMutation触发组件重渲染并忽略其返回结果
问题原因
Apollo的useMutation钩子默认会跟踪请求的loading、error、data状态,只要这些状态发生变更(比如请求开始、请求结束),就会触发所在组件重渲染,哪怕你没有显式使用这些返回值。
解决方案
方案1:开启ignoreResults配置(推荐,Apollo Client 3.4+支持)
直接在useMutation的第二个配置参数中设置ignoreResults: true,开启后钩子会完全忽略mutation的返回结果,也不会更新内部状态,自然不会触发组件重渲染:
const [myMutation] = useMutation(gql` mutation Test($updateUserId: ID!, $updateUserInput: UpdateUserInput!) { updateUser(id: $updateUserId, input: $updateUserInput) { id firstname age } } `, { ignoreResults: true // 新增该行配置即可 });
该配置不会影响mutation的正常发送,只是不会把返回结果同步到钩子的状态里,完全匹配你的需求。
方案2:直接调用client.mutate(兼容旧版本)
如果你使用的Apollo Client版本低于3.4,没有ignoreResults配置,可以不用useMutation钩子,直接通过useApolloClient拿到客户端实例手动调用mutation,这个方法不会绑定任何组件状态,不会触发重渲染:
import { useApolloClient, gql } from '@apollo/client'; const App = () => { const client = useApolloClient(); // Runs every time this component is rendered console.log("rendered"); // Called when the button is clicked const update = () => { client.mutate({ mutation: gql` mutation Test($updateUserId: ID!, $updateUserInput: UpdateUserInput!) { updateUser(id: $updateUserId, input: $updateUserInput) { id firstname age } } `, variables: { updateUserId: 1, updateUserInput: { age: Math.round(Math.random() * 10 + 5) // Set a random age from 5 - 15 } } }); }; return ( <> <h1>Update Test</h1> <button onClick={update}>Update!</button> </> ); };
内容的提问来源于stack exchange,提问作者Ayush Garg
相关产品推荐
相关产品推荐

