Save page state in React/implement vue's keep-alive/React Activation in react

1. Background
The user visits a list page and clicks to enter the details page. When returning to the list page from the details page, he needs to stay at the browsing position when he left the list page. In React, we usually use
routing to manage different pages. When switching pages, the routing will unload the unmatched page components. Therefore, in the above list page example, when the user returns to the list page from the details page, he will return to the top of the list page because the list page components are rebuilt after being uninstalled by the routing , the state is lost.

2. Common solutions
(1) Manually save the state : cooperate with the componentWillUnmount life cycle of the React component to save the data through data flow management tools such as dva and redux, and restore the data through the componentDidMount cycle. This method requires manual saving and restoring data every time, and like our own encapsulated list component, data request and rendering are performed on the component, which makes it impossible to save and restore data in the project.
(2) Control through styles : The list and details page are written on the same page, and the display and hiding of components are controlled through styles. This method involves large code changes and poor experience.

3. Automatically save status
(1) Commonly used wheel analysis

components
react-live-route The implementation cost is also relatively high, and it is necessary to pay attention to the preservation of the original function and the compatibility of multiple react-router versions
react-keeper Completely replacing the routing scheme is a risky thing that needs to be considered carefully
react-keep-alive Implementation of real KeepAlive function
react-router-cache-route Since it is no longer a component unloading, it does not cooperate well with TransitionGroup, which makes the transition animation difficult to achieve
react-activation Its children attribute is extracted and rendered into a component that will not be unloaded.

(2) Based on our configurable routing, minimal business code changes, and the capabilities provided by components, we finally chose react-activation.

import React, { Component } from 'react';
import KeepAlive, { withActivation } from 'react-activation';
import CachePage from './keepalive';

@CachePage
@withActivation
class Test extends Component {
  constructor(props) {
    super(props);
    this.state = {
      datalist: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,26, 27, 28, 29, 30],
    };
  }
  // 类组件要配合withActivation装饰器,才能使用componentDidActivat与componentWillUnactivate 对应激活与缓存两的生命周期
  // 函数组件可直接使用useActivate 与 useUnactivate hooks 钩子
  componentDidActivate() {
    console.log('激活页面——componentDidActivate')
  }
  componentWillUnactivate() {
    console.log('缓存页面——componentWillUnactivate')
  }
  render() {
    const { datalist } = this.state;
    return (
      <div>
        {datalist.map((item) => {
          return (
            <p key={item}>test——{item}</p>
          );
        })}
      </div>
    );
  }
}
export default Test;

/** keepalive.js **/
import React from 'react';
import KeepAlive from 'react-activation';
const CachePage = WrapperComponent => props => {
  const { location:{ pathname, search } } = props;
  return (
    <KeepAlive name={pathname} id={`${pathname}${search}`} when saveScrollPosition='screen'>
      <WrapperComponent {...props} />
    </KeepAlive>
  );
};
export default CachePage;

Note:
1. KeepAlive cannot be applied to state management . The same page with different routing parameters and different IDs will be cached in multiple copies. However, if the page data is managed by the model, it will cause data confusion, because only the page is cached and the data in the state management changes.
Solution : When the data managed by the model is injected, instead of using it directly, it can be converted into the component's state, so that it can follow the KeepAlive state.
2. Only components inside KeepAlive can respond to the cache life cycle. 3. Routes when true will be saved forever. Don’t forget to clear the cache
at the appropriate time. 4. Jump to an external page or use window.location.href to jump to this project. When the page returns again, the page is remounted without caching

For details on how to use it, please refer to the document, the author wrote it in detail https://github.com/CJY0208/react-activation/blob/master/README_CN.md

Guess you like

Origin blog.csdn.net/weixin_38649188/article/details/118578867