How to stop the previous component from rendering when it is redirected to another component in react

Viewed 21

SO I have two components :

  • mobiles
  • mobile detail

Initial state looks something like this:

const initialState = {
   data: [],
   loading: false,
   error: ''
};

When I fetch all the mobiles , it is stored in state.data . When user clicks on a mobile, It's id is sent to component Mobile detail

 viewDetails(id) {
    this.props.history.push("/detail", { selectedMobile: id });
  }

Now, In mobile detail component , I fetch the detail of the mobile and try to store it in state.data.

componentDidMount() {
    const selectedMobile = this.props.location.state.selectedMobile;
    this.props.loadMobile(selectedMobile);
  }

<Layout>
        <Switch>
     <div>
     <Route path="/detail" component={MobileDetail} />
     <Route path="/" component={Mobile} />
     </div> 
     </Switch>
     </Layout>

If you see the image below, mobile details component is loading the mobile component as well. What could be the reason behind this ?

enter image description here

1 Answers

Change your App.js to this

<Layout>

               <Switch>

            <Route path="/detail" component={MobileDetail} />

            <Route path="/" component={Mobile} /> 

            </Switch>

            </Layout>
Related