切换模态可见性时如何防止组件重新加载?

问题描述 投票:0回答:1

我在 RN 应用程序中使用

Modal
向用户显示地图。该组件加载缓慢且昂贵,这就是为什么我想确保它不会每次都从头开始加载。

但是,目前这不起作用。通过切换

visible
,每次模式再次打开时,地图组件都会从头开始加载。

有没有办法防止这种行为并确保地图不会每次都卸载并重新加载?

import { Modal } from 'react-native';

<Modal
  animationType="slide"
  transparent={true}
  visible={showModal}
  onRequestClose={() => setShowModal(false)}>
  <MapView onTogglePressed={() => setShowModal(false)} />
</Modal>
react-native
1个回答
0
投票

为了防止每次模态再次打开时地图组件被卸载并重新加载,您可以将地图组件的状态提升到模态组件之外。这样,每次切换模态时,地图组件就不会重新渲染。

以下是重构代码的方法:

import React, { useState } from 'react';
import { Modal, View, Button } from 'react-native';
import MapView from './MapView'; // Import your MapView component here

const MapModal = () => {
  const [showModal, setShowModal] = useState(false);

  return (
    <View style={{ flex: 1 }}>
      <Button title="Open Map" onPress={() => setShowModal(true)} />
      <Modal
        animationType="slide"
        transparent={true}
        visible={showModal}
        onRequestClose={() => setShowModal(false)}
      >
        <MapView onTogglePressed={() => setShowModal(false)} />
      </Modal>
    </View>
  );
};

export default MapModal;

在这个重构的代码中:

MapView 组件在 MapModal 组件内呈现。

状态 showModal 被提升到 MapModal 组件。

MapView 组件根据 showModal 状态有条件地渲染。

当模态关闭时,showModal 状态更新为 false,但 MapView 组件并未卸载。

它将保留其状态,并且当再次打开模态框时不会重新加载。

© www.soinside.com 2019 - 2024. All rights reserved.