If you've used [Vue](https://vuejs.org/), you know that it has a very good component ([keep-alive](https://vuejs.org/v2/guide/components-dynamic-async.html)) that keeps the state of the component to avoid repeated re-rendering.
Sometimes, we want the list page to cache the page state after the list page enters the detail page. When the detail page returns to the list page, the list page is still the same as before the switch.
Oh, this is actually quite difficult to achieve, because the components in React cannot be reused once they are uninstalled. Two solutions are proposed in [issue #12039](https://github.com/facebook/react/issues/12039). By using the style switch component display (display:none | block;), this can cause problems, such as when you switch components, you can't use animations; or use data flow management tools like Mobx and Redux, but this is too much trouble.
In the end, I implemented this effect through the [React.createPortal API](https://reactjs.org/docs/portals.html). `react-keep-alive` has two main components `<Provider>` and `<KeepAlive>`. The `<Provider>` is responsible for saving the component's cache and rendering the cached component outside of the application via the React.createPortal API before processing. The cached components must be placed in `<KeepAlive>`, and `<KeepAlive>` will mount the components that are cached outside the application to the location that really needs to be displayed.
## API Reference
### `Provider`
...
...
@@ -198,49 +163,16 @@ class One extends React.Component {
}
}
class Two extends React.Component {
render() {
return (
<div>This is Two.</div>
);
}
}
class App extends React.Component {
handleActivate = () => {
console.log('One activated');
}
handleUnactivate = () => {
console.log('One unactivated');
}
render() {
return (
<div>
<ul>
<li>
<Link to="/one">one</Link>
</li>
<li>
<Link to="/two">two</Link>
</li>
</ul>
<Switch>
<Route path="/one">
<KeepAlive
key="One"
onActivate={this.handleActivate}
onUnactivate={this.handleUnactivate}
>
<KeepAlive key="One">
<One />
</KeepAlive>
</Route>
<Route path="/two">
<KeepAlive key="Two">
<Two />
</KeepAlive>
</Route>
</Switch>
</div>
);
...
...
@@ -270,19 +202,9 @@ import {
import {
Provider,
KeepAlive,
bindLifecycle,
} from 'react-keep-alive';
@bindLifecycle
class One extends React.Component {
componentDidMount() {
console.log('One componentDidMount');
}
componentWillUnmount() {
console.log('One componentWillUnmount');
}
render() {
return (
<div>This is One.</div>
...
...
@@ -290,49 +212,16 @@ class One extends React.Component {