简体   繁体   中英

Dynamic routing and lifecycle in react

I'm working with dynamic routing in react. I'm fetching some data from a third-party API. I have my dynamic route to be something like this

<Route path="/:id" component = {item} />

In the item component, I get the value in params.id and use that id to fetch my data in

componentDidUpdate(){ fetchData(this.props.match.params.id);}

The issue I'm having now is that whenever I try to visit another route of the same format /:id from the Item component, the params changes to the new id passed but still retains the old content for the old id. I believe componentDidmount wasn't called since i'm in that same item component. the component wasn't remounted but just updated. What can I do?

You have to make the api call in componentDidMount as well as in componentDidUpdate with class component. Once you fetch the data, you have to set it in state of the component to visually see it.

componentDidmount() {
  fetchData(this.props.match.params.id);
}

componentDidUpdate(prevProps, prevState){
  if(prevProps.match.params.id !== this.props.match.params.id) {
    fetchData(this.props.match.params.id);
  }
}

If you rather use react hooks + functional component, this will be simplified for you. You can use useState to maintain data in the state.

import React, { useEffect } from "react";
const YourComponent = props => {
    const { id } = props.match.params;
    // This will run every time id changes.
    useEffect(() => {
        fetchData(id);
    }, [id]); 

    return (
        <>
            Your api call
        </>
    );
};

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