简体   繁体   中英

history.push does not re-render/refresh component in React/Typescript

I am navigating to a component that has ajax request, however the ajax call is only called on the first time the component is navigated to. All other routes look ok but this is the route with the problem:

    const history = useHistory();

    onClick={() => history.push(`/details/${id}`}

Routes:

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;

Component 2 code:

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;

Now it's more clear what could cause the problem: looks like you are trying to fetch json from the same path, where you return the actual page. In other words you have to decide what do you expect from server when you request /detail/${id} : a page or a json. If server is already set up to return json, then you have to assign a different path for the page. But I would change the path to json to something like /api/detail/${id} instead, because normally people make /api/* routes for requesting json data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM