如何将渲染的组件保存到内存中?

lau*_*ent 6 javascript caching rendering reactjs react-native

我正在开发一个由多个屏幕组成的 React Native 应用程序(尽管我认为我的问题通常适用于 React)。

所以我创建了一个简单的组件来切换屏幕:

import React, { Component } from 'react';
import { connect } from 'react-redux'
import { View } from 'react-native';

class AppNavComponent extends Component {

    constructor() {
        super();
        this.screenCache_ = {};
    }

    render() {
        if (!this.props.route) throw new Error('Route must not be null');
        let route = this.props.route;
        if (this.screenCache_[route.routeName]) return this.screenCache_[route.routeName];
        let Screen = this.props.screens[route.routeName].screen;

        this.screenCache_[route.routeName] = (
            <View>
                <Screen/>
            </View>
        );

        return this.screenCache_[route.routeName];
    }

}

const AppNav = connect(
    (state) => {
        return {
            route: state.route,
        };
    }
)(AppNavComponent)

export { AppNav };
Run Code Online (Sandbox Code Playgroud)

this.props.screens包含屏幕列表,以及this.props.route需要显示的路线。该组件工作正常,但我的问题是我想将某些屏幕缓存到内存中,因为它们渲染很慢(一个大列表)并且每当 React 重新渲染它们时它们都会丢失滚动位置。

在上面的示例中,我尝试将渲染保存到,this.screenCache_但这可能不是正确的方法,因为当我加载屏幕、转到另一个页面并返回到它们时,屏幕仍在重新渲染。

我想这是一个常见问题,但我在 Google 上找不到任何信息。关于如何做到这一点的任何建议?

Lyu*_*mir 6

没有办法按照你的方式有效地缓存组件,因为 DOM 稍后仍然需要重新绘制它,这是最重要的部分。

一个更简单的解决方案,我认为 slack 在幕后做到了,是使用display: none

<View style={shouldDisplayScreen ? {} : { display: none }} />


附注。如果当前未显示组件以避免性能问题,您可能希望设置shouldComponentUpdatefalse