React實現組件緩存的一種思路


前言

  • 對於某個頁面中的某個組件,很多時候需要其保持一直激活的狀態,之前我的博客里面有一篇提到一種緩存策略,就是利用Routechildren方法來display該組件或隱藏該組件。但是這種方式需要借助到Route組件並且只能緩存整個頁面,而不是頁面中的部分組件。並且這種緩存單純的只是在頁面上把它的display變成了blocknone,僅僅是在路由離開的時候不卸載掉該組件。
  • 對此,還有一種思路也可以嘗試一下,就是在一個組件離開前去保存它所有的state值,等到下次渲染組件的時候把上次卸載錢的state值還原回來,不就可以使得,組件重新渲染后依然是上一次離開前的狀態嗎。

實現思路

  • 給需要緩存的組件加一層高階組件,在高階組件中通過ref獲取到該組件的實例。
  • ComponentDidMount中通過ref獲取到的實例,調用組件的setState方法,把緩存的上一次的state數據注入進去。
  • ComponentWillUnmount中通過ref獲取到的實例,去獲取其所有state的值,並存在緩存中。

代碼實現

const keepAlive = (Comp) => {

  let cache = {};

  return class Alive extends React.Component {

    componentDidMount() {
      const state = this.comp.state;
      this.comp.setState({ ...state, ...cache });
    }

    componentWillUnmount() {
      const state = this.comp.state;
      cache = { ...state };
    }

    render() {
      return (
        <Comp ref={comp => this.comp = comp} { ...this.props } />
      )
    }
  }
}
  • 使用
import React from 'react';
import keepAlive from 'keep-alive-react';

class Test extends React.Component {
  state = {
    count: 0
  }

  render() {
    const { count } = this.state;
    return (
      <div className="Test">
      Test
      <div>count: {count}</div>
      <div onClick={() => {
        this.setState({
          count: count + 1
        })
      }}>add</div>
    </div>
    );
  }
}

export default keepAlive(Test);

小結

  • 目前該實現方式,暫不能支持函數式組件,函數式組件的狀態都是使用的hooks寫法,而hooks寫法中無法便捷統一的去獲取其組件所有的state值,並且也無法針對函數式組件去拿到該組件內部的引用,導致該思路只能給繼承自React.Component的組件使用。
  • 該方法已經發布到npm上。直接使用npm i keep-alive-react --save就可以像示例中一樣進行全局引用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM