我正在导航到一个具有ajax请求的组件,但是ajax调用仅在该组件第一次被导航到时调用。所有其他路由看起来都没问题,但这是有问题的路由:
const history = useHistory();
onClick={() => history.push(`/details/${id}`}
路线:
import React from 'react';
import { BrowserRouter, Route, Switch} from 'react-router-dom';
import { QueryClient, QueryClientProvider } from 'react-query';
import { RouteComponentProps } from "react-router-dom";
import Component1 from '../Component1';
import Component2 from '../Component2';
const queryClient = new QueryClient()
const Routing: React.FunctionComponent = () => {
return (
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<Switch>
<Route exact path="/" component={Component1} />
<Route path="/details/:id" render={(props: RouteComponentProps<any>) => <Component2 {...props}/>} />
<Route component={NotFound} />
</Switch>
</BrowserRouter>
</QueryClientProvider>
)
}
export default Routing;
组件2代码:
import React from 'react';
import { RouteComponentProps, useLocation } from "react-router-dom";
import { useQuery, useQueryClient} from 'react-query';
const Component2: React.FunctionComponent<RouteComponentProps<any>> = (props) => {
const { state } = useLocation<stateType>();
let id = props.match.params.id;
const fetchData = async () => {
const res = await fetch(`/detail/${id}`);
return res.json();
};
const { data, status } = useQuery('chartInfo', fetchData, {
staleTime: 5000,
});
return (
{status === 'error' && (
<div className="mt-5">Error fetching data!</div>
)}
{status === 'loading' && (
<div className="mt-5">Loading data ...
</div>
)}
{status === 'success' && (
<div className="mt-5">
// data binded here
</div>
)}
)
}
export default Component2;
现在更清楚是什么可能导致这个问题:看起来你正试图从相同的路径获取json,你返回实际的页面。换句话说,当您请求/detail/${id}
时,您必须决定您期望从服务器获得什么:页面还是json。如果服务器已经设置为返回json,那么您必须为页面分配不同的路径。但我会将路径改为json,改为/api/detail/${id}
,因为通常人们会用/api/*
路由请求json data