Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent react router from re-rendering a previously rendered page?

I think I've got some issue with react router. How can I prevent react router from re-rendering a previously rendered page?

I have router code like this:

class App extends React.Component {
  render() {
    return (
        <div>
            <NavBar/>
            {this.props.children}
        </div>
    );
  }
}

ReactDOM.render(
    (
        <Router history={hashHistory}>
            <Route path="/" component={App}>
                <IndexRoute component={Gateway} />
                <Route path="home" component={Gateway} />
                <Route path="categories" component={Categories} />
            </Route>
        </Router>
    ), document.getElementById('my-app')
);

When I first visit the page, it hits index, Gateway component got rendered. Then I click on "categories" link, and Categories component got rendered. Then when I click "home" link again, the component Gateway got re-rendered. Its state got RESET. This is really frustrating, as I could not figure our why its state got reset.

Is there any solution for this?

like image 915
Ian Avatar asked Feb 14 '17 06:02

Ian


1 Answers

If there is any state you want to be saved, you should store it somewhere, such as the component's state (or the redux state if you use redux).

In react, you can define the function shouldComponentUpdate() within components in order to force React not to re-render your DOM. But in the case of the react-router, the DOM of the first route is destroyed (not just hidden) and therefore should be re-rendered.

like image 135
Antoine Trouve Avatar answered Oct 13 '22 21:10

Antoine Trouve