const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
<React.StrictMode>
<ErrorBoundary fallback={<ErrorMessage />}>
<Suspense fallback={<Loading />}>
<App />
</Suspense>
</ErrorBoundary>
</React.StrictMode>
);
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import DogList from './components/Dog/DogLIst';
const queryClient = new QueryClient({
defaultOptions: {
queries: {
throwOnError: true,
},
mutations: {
throwOnError: true,
},
},
});
function App() {
return (
<QueryClientProvider client={queryClient}>
<DogList />
</QueryClientProvider>
);
}
export default App;
import { useSuspenseQuery } from '@tanstack/react-query';
import axios from 'axios';
type DogType = {
id: string;
url: string;
width: number;
height: number;
};
const DogList = () => {
const fetchDogList = async () => {
const response = await axios.get('https://api.thecatapi.com/v0/images/search?limit=10');
return response.data;
};
const { data: list } = useSuspenseQuery<DogType[]>({
queryKey: ['doglist'],
queryFn: fetchDogList,
retry: 0,
});
return (
<div style={{ margin: '3rem auto', textAlign: 'center' }}>
{list &&
list.map((item) => (
<div key={item.id}>
<img src={item.url} alt={item.id} width="300px" height="300px" />
</div>
))}
</div>
);
};
export default DogList;
我故意在 DogList 组件中生成 api 错误。
然后,由于 App 组件被包装在 ErrorBoundary 中,因此应该显示回退,但会出现运行时错误,如下所示。也许它没有检测到运行时错误
如何全局处理错误?
您可能必须将
<QueryClientProvider client={queryClient}>
放在树中比边界和悬念更高的位置。