可以使用Apollo的refetchQueries选项来刷新缓存,即在重定向之前重新获取数据。 例如,在使用react-router-dom重定向时,可以在重定向语句中使用withRouter封装组件,并在重定向之前调用Apollo的refetchQueries选项,以确保缓存中包含最新的数据。以下是一个示例代码:
import React from 'react';
import { withRouter } from 'react-router-dom';
import { useMutation } from '@apollo/client';
import { MY_MUTATION } from './mutations';
import MyComponent from './MyComponent.jsx';
const MyContainer = ({ history }) => {
const [myMutation] = useMutation(MY_MUTATION, {
// 使用refetchQueries选项刷新缓存
refetchQueries: ['myQuery'],
onCompleted() {
// 重定向到新页面
history.push('/newPage');
},
});
const handleButtonClick = () => {
myMutation();
};
return (
);
};
export default withRouter(MyContainer);