延遲載入是一種僅在需要時才載入資源的設計模式。這有利於改善 React Native 應用程式的初始載入時間,減少記憶體消耗,提高整體效能。
為什麼要延遲載入?
- 效能最佳化:防止應用程式首次啟動時載入不必要的資源,從而顯著減少載入時間。
- 減少記憶體使用:延遲載入可防止在不需要時將映像、元件或外部函式庫等大型資源保留在記憶體中。
- 改進的使用者體驗:按需載入資源提供更流暢的導航和互動。
1) React Native 螢幕/元件中延遲載入的用例
延遲載入畫面(程式碼分割):
在 React Native 中,延遲載入通常用於元件,特別是當您有用戶可能不經常存取的不同螢幕時。透過延遲載入這些螢幕,您可以減小初始包的大小。使用 React.lazy() 和 Suspense 進行延遲載入:
React 引入了 React.lazy() 函數來啟用元件的延遲載入。若要使用延遲加載,可使用 Suspense 作為後備,直到元件加載。
正常使用
在正常使用中,所有資源、元件、程式庫和資料都會在應用程式啟動時預先載入。這種方法適用於小型應用程序,但隨著應用程式的成長,可能會變得效率低下且資源密集,從而影響效能和載入時間。
範例:正常組件加載
import React from 'react'; import HomeScreen from './screens/HomeScreen'; import ProfileScreen from './screens/ProfileScreen'; const App = () => { return ( <homescreen></homescreen> <profilescreen></profilescreen> > ); }; export default App;
說明:
- 在此範例中,HomeScreen 和 ProfileScreen 元件都是預先匯入和載入的,無論使用者是否導航到它們。
- 這會增加初始載入時間,因為所有元件都會立即捆綁並載入。
延遲載入用法
透過延遲加載,元件、庫或資料僅在需要時加載。由於僅按需載入必要的資源,因此可以透過減少初始載入時間和記憶體使用量來提高效能。
範例:延遲載入元件
import React, { Suspense, lazy } from 'react'; import { ActivityIndicator } from 'react-native'; const HomeScreen = lazy(() => import('./screens/HomeScreen')); const ProfileScreen = lazy(() => import('./screens/ProfileScreen')); const App = () => { return ( <suspense fallback="{<ActivityIndicator" size="large" color="#0000ff"></suspense>}> <homescreen></homescreen> <profilescreen></profilescreen> ); }; export default App;
說明:
- 在此範例中,HomeScreen 和 ProfileScreen 是使用 React.lazy() 延遲載入的。
- 在載入這些元件之前,會顯示後備(ActivityIndicator)。
- 這減少了應用程式的初始載入時間,因為元件僅在渲染時載入。
正常載入和延遲載入之間的差異
Feature | Normal Usage | Lazy Loading |
---|---|---|
Loading Strategy | Everything is loaded upfront when the app starts. | Components, resources, or data are loaded only when needed. |
Initial Load Time | Higher, as all resources are loaded at once. | Lower, as only essential components are loaded upfront. |
Memory Usage | Higher, as all components and resources are loaded into memory. | Lower, as only necessary components are loaded into memory. |
User Experience | Slower startup but smoother transitions once loaded. | Faster startup but slight delay when loading resources. |
Best for | Small applications with limited components. | Large applications where not all components are used initially. |
Implementation | Simpler, as everything is bundled at once. | Requires managing dynamic imports and possibly loading states. |
2. Lazy Loading in Navigation (React Navigation):
Lazy loading ensures that screens or components are only mounted when they are accessed (when the user navigates to them), thus improving performance, especially in apps with multiple screens.
Example: Lazy Loading in React Navigation (Stack Navigator)
import React, { Suspense, lazy } from 'react'; import { createStackNavigator } from '@react-navigation/stack'; import { NavigationContainer } from '@react-navigation/native'; import { ActivityIndicator } from 'react-native'; // Lazy load screens const HomeScreen = lazy(() => import('./screens/HomeScreen')); const ProfileScreen = lazy(() => import('./screens/ProfileScreen')); const Stack = createStackNavigator(); const App = () => { return ( <navigationcontainer> <stack.navigator> <stack.screen name="Home" component="{()"> ( <suspense fallback="{<ActivityIndicator" size="large" color="#0000ff"></suspense>}> <homescreen></homescreen> )} /> <stack.screen name="Profile" component="{()"> ( <suspense fallback="{<ActivityIndicator" size="large" color="#0000ff"></suspense>}> <profilescreen></profilescreen> )} /> </stack.screen></stack.screen></stack.navigator> </navigationcontainer> ); }; export default App;
Explanation:
- In this example, the HomeScreen and ProfileScreen components are lazily loaded using React.lazy().
- The Suspense component provides a loading indicator (ActivityIndicator) while the components are being loaded.
- Screens will only load when the user navigates to them, reducing the initial load time.
3. Lazy Loading Images :
In React Native, lazy loading can be achieved using libraries like react-native-fast-image or manually handling image loading by tracking visibility with tools like IntersectionObserver.
a) Using react-native-fast-image
react-native-fast-image is a performant image component that provides built-in lazy loading.
npm install react-native-fast-image
Example: Lazy Loading Images with react-native-fast-image
import React from 'react'; import { View, ScrollView, Text } from 'react-native'; import FastImage from 'react-native-fast-image'; const LazyLoadingImages = () => { return ( <scrollview> <text>Scroll down to load images</text> <fastimage style="{{" width: height: source="{{" uri: priority: fastimage.priority.normal resizemode="{FastImage.resizeMode.contain}"></fastimage> <fastimage style="{{" width: height: source="{{" uri: priority: fastimage.priority.normal resizemode="{FastImage.resizeMode.contain}"></fastimage> </scrollview> ); }; export default LazyLoadingImages;
Explanation:
- The FastImage component from react-native-fast-image helps with lazy loading. It loads images only when they are about to be displayed.
- It also provides efficient caching and priority options, improving performance.
b) Manual Lazy Loading (Visibility Tracking)
In cases where you don't want to use a third-party library, you can implement lazy loading by tracking when an image enters the viewport using tools like IntersectionObserver (web) or a custom scroll listener in React Native.
Example: Lazy Loading with Visibility Tracking (using React Native)
import React, { useState, useEffect } from 'react'; import { View, Image, ScrollView } from 'react-native'; const LazyImage = ({ src, style }) => { const [isVisible, setIsVisible] = useState(false); const onScroll = (event) => { // Implement logic to determine if image is visible based on scroll position const { y } = event.nativeEvent.contentOffset; if (y > 100) { // Example: load image when scrolled past 100px setIsVisible(true); } }; return ( <scrollview onscroll="{onScroll}" scrolleventthrottle="{16}"> <view> {isVisible ? ( <image source="{{" uri: src style="{style}"></image> ) : ( <view style="{style}"></view> )} </view> </scrollview> ); }; const App = () => { return ( <lazyimage src="https://example.com/my-image.jpg" style="{{" width: height:></lazyimage> ); }; export default App;
Explanation:
- The LazyImage component only loads the image once the user has scrolled a certain amount (onScroll event).
- This approach manually tracks the scroll position and loads the image accordingly.
4. Lazy Loading with Redux (Dynamic Reducers) :
When using Redux, you may want to lazy load certain reducers only when necessary, such as for specific screens or features.
- Create a function to inject reducers dynamically.
- Add the new reducer to the Redux store when needed (e.g., when a user navigates to a new screen).
- Remove the reducer when it is no longer needed (optional).
Example: Lazy Loading Reducers in a React Application with Redux
1. Initial Redux Store Setup
Start by setting up a standard Redux store, but instead of adding all reducers upfront, create an injection method.
import { configureStore, combineReducers } from '@reduxjs/toolkit'; const staticReducers = { // Add reducers that are needed from the start }; export const createReducer = (asyncReducers = {}) => { return combineReducers({ ...staticReducers, ...asyncReducers, }); }; const store = configureStore({ reducer: createReducer(), }); // Store injected reducers here store.asyncReducers = {}; export default store;
In the above code:
- staticReducers: Contains reducers that are loaded when the app starts.
- asyncReducers: This object will contain dynamically injected reducers as they are loaded.
2. Dynamic Reducer Injection Method
Create a helper function to inject new reducers dynamically into the store.
// Helper function to inject a new reducer dynamically export function injectReducer(key, asyncReducer) { if (!store.asyncReducers[key]) { store.asyncReducers[key] = asyncReducer; store.replaceReducer(createReducer(store.asyncReducers)); } }
The injectReducer function checks if a reducer has already been added. If not, it injects it into the store and replaces the current root reducer.
3. Loading Reducer When Needed (Lazy Loading)
Imagine you have a new page or feature that needs its own reducer. You can inject the reducer dynamically when this page is loaded.
import { lazy, Suspense, useEffect } from 'react'; import { useDispatch } from 'react-redux'; import { injectReducer } from './store'; import featureReducer from './features/featureSlice'; // The reducer for this feature const FeatureComponent = lazy(() => import('./components/FeatureComponent')); const FeaturePage = () => { const dispatch = useDispatch(); useEffect(() => { injectReducer('feature', featureReducer); // Dynamically load the reducer }, [dispatch]); return ( <suspense fallback="{<div">Loading...}> <featurecomponent></featurecomponent> </suspense> ); }; export default FeaturePage;
Here:
- When the FeaturePage component is loaded, the injectReducer function adds the featureReducer dynamically to the Redux store.
- The Suspense component handles lazy loading of the FeatureComponent.
4. Feature Reducer Example
The reducer for the feature is written as usual, using Redux Toolkit.
import { createSlice } from '@reduxjs/toolkit'; const featureSlice = createSlice({ name: 'feature', initialState: { data: [] }, reducers: { setData: (state, action) => { state.data = action.payload; }, }, }); export const { setData } = featureSlice.actions; export default featureSlice.reducer;
Removing a Reducer (Optional)
You might want to remove a reducer when it's no longer needed, for example, when navigating away from a page.
Here’s how you can remove a reducer:
export function removeReducer(key) { if (store.asyncReducers[key]) { delete store.asyncReducers[key]; store.replaceReducer(createReducer(store.asyncReducers)); } }
You can call this function when a feature or page is unmounted to remove its reducer from the store.
5. Lazy Loading Libraries/Packages:
If you are using heavy third-party libraries, lazy loading them can help optimize performance.
import React, { useState } from 'react'; const HeavyComponent = React.lazy(() => import('heavy-library')); // React.lazy(() => import('moment')) const App = () => { const [showComponent, setShowComponent] = useState(false); return ( <view> <button title="Load Heavy Component" onpress="{()"> setShowComponent(true)} /> {showComponent && ( <suspense fallback="{<Text">Loading...}> <heavycomponent></heavycomponent> </suspense> )} </button></view> ); };
- Lazy Loading Data: You can also implement lazy loading for data fetching, where data is fetched in chunks or when a user scrolls (infinite scroll).
Example: Lazy Loading Data:
import React, { useState, useEffect } from 'react'; import { FlatList, ActivityIndicator, Text } from 'react-native'; const LazyLoadData = () => { const [data, setData] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(json => { setData(json); setLoading(false); }); }, []); if (loading) { return <activityindicator></activityindicator>; } return ( <flatlist data="{data}" renderitem="{({" item> <text>{item.name}</text>} keyExtractor={item => item.id} /> ); }; export default LazyLoadData; </flatlist>
Explanation:
- Fetching data lazily ensures that the app doesn’t load too much data at once, improving performance and reducing bandwidth usage.
Summary of Use Cases:
- Screens/Components: Lazy loading React Native screens or components using React.lazy() and Suspense.
- Images: Lazy loading images as they enter the viewport to save memory and bandwidth.
- Redux Reducers: Injecting reducers dynamically to reduce the initial store size in Redux.
- Libraries: Lazily load third-party libraries or packages to reduce the initial bundle size.
- Data: Implement lazy loading for large datasets using techniques like pagination or infinite scrolling.
Lazy loading helps improve the performance, memory usage, and user experience of your React Native app, making it more efficient and responsive for users.
以上是掌握 React Native/ReactJS 中的延遲載入概念的詳細內容。更多資訊請關注PHP中文網其他相關文章!

C 和JavaScript通過WebAssembly實現互操作性。 1)C 代碼編譯成WebAssembly模塊,引入到JavaScript環境中,增強計算能力。 2)在遊戲開發中,C 處理物理引擎和圖形渲染,JavaScript負責遊戲邏輯和用戶界面。

JavaScript在網站、移動應用、桌面應用和服務器端編程中均有廣泛應用。 1)在網站開發中,JavaScript與HTML、CSS一起操作DOM,實現動態效果,並支持如jQuery、React等框架。 2)通過ReactNative和Ionic,JavaScript用於開發跨平台移動應用。 3)Electron框架使JavaScript能構建桌面應用。 4)Node.js讓JavaScript在服務器端運行,支持高並發請求。

Python更適合數據科學和自動化,JavaScript更適合前端和全棧開發。 1.Python在數據科學和機器學習中表現出色,使用NumPy、Pandas等庫進行數據處理和建模。 2.Python在自動化和腳本編寫方面簡潔高效。 3.JavaScript在前端開發中不可或缺,用於構建動態網頁和單頁面應用。 4.JavaScript通過Node.js在後端開發中發揮作用,支持全棧開發。

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。1)C 用于解析JavaScript源码并生成抽象语法树。2)C 负责生成和执行字节码。3)C 实现JIT编译器,在运行时优化和编译热点代码,显著提高JavaScript的执行效率。

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版
SublimeText3 Linux最新版

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3漢化版
中文版,非常好用

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)