[Vuejs]-How to avoid component rerendering when route change which similar to keep-alive in vuejs?

0👍

It seems that react doesn’t support the similar feature keep-alive. We need to implement it by ourselves.

According to the source code of keep-alive component of vue, we need to cache the virtual dom (vnode in vue) of children in state. The keep-alive component is the wrapper of router, thus the cache will never be pruned when router changed.

In addition, I have a simple approach in my app, if you don’t care about
the performance. The main idea is to hide/show the view component on router changing event, instead of mount/unmount.

<Router>
  <Layout>
    <Switch>
      <Route path="/foo" component={Foo} />
      <Route path="/bar" component={Bar} />
    </Switch>
    // the alive route match any path so that it will be never rerendered
    <Route path="/:any" component={AliveComponent} />
  <Layout>
</Router>

Codes in AliveComponent:

...
state = {isShown: false};
componentWillMount () {
  const {history, location} = this.props;
  this.setState({isShown: location.pathname === '/alive-view-path'});

  const unlistenHistory = history.listen(
    ({pathname, state}, action) => {
      this.setState({isShown: pathname === '/alive-view-path'});
    }
  );
  this.setState({unlistenHistory});
}
componentWillUnmount () {
  if (_.isFunction(this.state.unlistenHistory)) {
    this.state.unlistenHistory();
  }
}
render () {
  return <div style={{display: this.state.isShown ? 'block' : 'none'}} />
}
...

Leave a comment