meg*_*ayu 5 apollo reactjs apollo-client
const App = () => {
const [myMutation] = useMutation(gql`
mutation Test($updateUserId: ID!, $updateUserInput: UpdateUserInput!) {
updateUser(id: $updateUserId, input: $updateUserInput) {
id
firstname
age
}
}
`);
// Runs every time this component is rendered
console.log("rendered");
// Called when the button is clicked
const update = () => {
myMutation({
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>
</>
);
};
Run Code Online (Sandbox Code Playgroud)
每当onClick调用时,整个组件都会重新渲染。这不是我想要的,因为我不关心突变的结果。有什么方法可以阻止myMutation重新渲染并完全忽略结果吗?
useMutation是一个钩子,它state里面有导致重新渲染的请参阅useMultation以下类型:
export interface MutationResult<TData = any> {
data?: TData | null;
error?: ApolloError;
loading: boolean;
called: boolean;
client: ApolloClient<object>;
}
Run Code Online (Sandbox Code Playgroud)
状态loading是导致重新渲染的原因,因此您在哪个组件中指定useMutation它会因此而重新渲染state
一种可能的解决方法是将组件与useMutation另一个组件分开
像这样的事情:
function App() {
return (
<>
<Header /> // <-- this coponent won't re-render
<UpdateUserButton /> // <-- useMutation is in here!
</>
);
}
Run Code Online (Sandbox Code Playgroud)
查看现场示例:
| 归档时间: |
|
| 查看次数: |
5678 次 |
| 最近记录: |