在使用Apollo Client时,有时会出现调用每个突变和查询时会调用两次的情况。以下是一种可能的解决方法:
ApolloProvider
提供Apollo Client时,确保只在根组件中提供一次,而不是在每个组件中都提供一次。import { ApolloProvider, ApolloClient, InMemoryCache } from '@apollo/client';
const client = new ApolloClient({
uri: 'http://your-graphql-api-endpoint',
cache: new InMemoryCache(),
});
ReactDOM.render(
,
document.getElementById('root')
);
React.memo
或useCallback
来避免不必要的重新渲染。import { useQuery } from '@apollo/client';
const MyComponent = React.memo(() => {
const { loading, error, data } = useQuery(MY_QUERY);
if (loading) return Loading...
;
if (error) return Error
;
return (
{/* render your component */}
);
});
render
方法中调用产生副作用的函数。可以将这些函数移动到componentDidMount
或componentDidUpdate
生命周期方法中。import { Query } from '@apollo/client/react/components';
class MyComponent extends React.Component {
componentDidMount() {
// call the mutation or query here
}
componentDidUpdate(prevProps) {
if (prevProps.someProp !== this.props.someProp) {
// call the mutation or query here
}
}
render() {
return (
{({ loading, error, data }) => {
if (loading) return Loading...
;
if (error) return Error
;
return (
{/* render your component */}
);
}}
);
}
}
通过检查以上几点,你应该能够解决调用每个突变和查询时会调用两次的问题。注意,这只是一种可能的解决方法,具体情况可能因你的代码结构和配置而有所不同。