简体   繁体   中英

react-router-dom refresh component when route changes

I used same component for different routes. When route changes, I want the component to be rendered.

<Switch>
    <Route exact path="/" component={HomePage} />
    <Route path="/hotels" component={HotelsPage} />
    <Route path="/apartments" component={HotelsPage} />
</Switch>

When I change the route path from /hotels to /apartments , the component HotelsPage doesn't refresh.

What is the cool approach for this?

您可以通过以下方式显式传递道具来进行排序:

<Route path="/hotels" component={props => <HotelsPage {...props} />} />

Firstly you can aggregate the Route into one like

<Switch>
    <Route exact path="/" component={HomePage} />
    <Route path="/(hotels|apartments)" component={HotelsPage} />
</Switch>

and secondly, your HotelsPage component is rendered both on /hotels , /apartments , it is similar case like path params, whereby the component doesn't mount again on path change, but updates thereby calling componentWillReceiveProps lifecycle function,

What you can do is implement componentWillReceiveProps like

componentWillReceiveProps(nextProps) {
    if (nextProps.location.pathname !== this.props.location.pathname) {
      console.log("here");
      //take action here
    }
  }

DEMO

I guess just passing useLocation().pathname will resolve issue

  useEffect(
    () => {
         // Your logics
        });
    }, [useLocation().pathname])

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