iT邦幫忙

2023 iThome 鐵人賽

0
Modern Web

React Native的學習與實作系列 第 18

【Day18】自訂元件(2)

  • 分享至 

  • xImage
  •  

1. 性能優化

在這一節,我們將討論如何透過一些性能優化的技巧,使React Native自訂元件更高效。包括:

  • shouldComponentUpdate方法: <shouldComponentUpdate>生命週期方法,以及如何使用它來避免不必要的重新渲染。這在某些情況下可以有效地減少元件的重繪,提高應用程式性能。
  • PureComponent: <PureComponent>是一個React Native提供的內建元件,可以自動實現shouldComponentUpdate,對於一些簡單的元件,使用它可以更輕鬆地進行性能優化。
import React, { PureComponent } from 'react';
import { View, Text } from 'react-native';

class OptimizedComponent extends PureComponent {
  render() {
    return (
      <View>
        <Text>Optimized Component</Text>
      </View>
    );
  }
}

2. Redux和自訂元件

整合Redux到React Native自訂元件中,實現全局狀態管理。包括:

  • Redux基本概念: 簡單介紹Redux的基本概念,包括Actions、Reducers和Store。
  • 連接自訂元件到Redux: 使用<connect>函數將自訂元件連接到Redux store,使其能夠訪問全局狀態。
  • 訂閱Redux store中的狀態: 展示如何在自訂元件中訂閱Redux store中的狀態,以實現動態更新。
import React from 'react';
import { View, Text } from 'react-native';
import { connect } from 'react-redux';

const ConnectedComponent = ({ myReduxState }) => {
  return (
    <View>
      <Text>{myReduxState}</Text>
    </View>
  );
};

const mapStateToProps = (state) => ({
  myReduxState: state.myReduxState,
});

export default connect(mapStateToProps)(ConnectedComponent);

3. 使用Hooks

在自訂元件中使用<useState><useEffect>將使元件的邏輯更簡潔,並提高可讀性。

  • useState: 展示如何使用<useState>來添加狀態到函數元件中
  • useEffect: 使用<useEffect>處理副作用,例如數據的加載和訂閱。
import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';

const HookedComponent = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    // 執行副作用
    console.log('Effect ran!');
  }, [count]); // 只有在count發生變化時執行

  return (
    <View>
      <Text>{count}</Text>
      <Button title="Increase Count" onPress={() => setCount(count + 1)} />
    </View>
  );
};

4. 測試自訂元件

Jest 是由 Facebook 開發的 JavaScript 測試框架,專為 React 應用程式而設計。它具有直觀的 API、快速且易於設置,是 React 生態系統中最流行的測試框架之一。

以下是使用 Jest 撰寫和運行測試的基本步驟:
安裝 Jest
首先,確保我們的 React Native 專案已經安裝了 <jest> @testing-library/react-native(React Native 的測試工具):

npm install --save-dev jest @testing-library/react-native

撰寫測試
假設我們有一個簡單的 React Native 元件:

// MyComponent.js
import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';

const MyComponent = ({ onPress, count }) => {
  return (
    <View>
      <Text>Count: {count}</Text>
      <TouchableOpacity onPress={onPress}>
        <Text>Increase Count</Text>
      </TouchableOpacity>
    </View>
  );
};

export default MyComponent;

接著,撰寫 Jest 測試。在專案的根目錄中,建立一個 __tests__ 目錄,然後在該目錄中建立與被測試檔案對應的測試檔案:

// __tests__/MyComponent.test.js
import React from 'react';
import { render, fireEvent } from '@testing-library/react-native';
import MyComponent from '../MyComponent';

test('renders component with initial count', () => {
  const { getByText } = render(<MyComponent count={0} />);
  expect(getByText(/Count: 0/)).toBeTruthy();
});

test('increases count when button is pressed', () => {
  const { getByText } = render(<MyComponent count={0} />);
  fireEvent.press(getByText('Increase Count'));
  expect(getByText(/Count: 1/)).toBeTruthy();
});

運行測試
package.json 中,添加以下 scripts:

"scripts": {
  "test": "jest"
}

然後運行測試

npm test

Jest 將會在 __tests__ 目錄中查找並執行所有測試檔案。測試結果將會顯示在終端機中。

Jest 提供了許多內建的匹配器(matchers)和功能,使得測試更容易理解和維護。此外,你可以透過配置 Jest,使其與其他工具整合,例如 Babel、Webpack、Enzyme 等。


上一篇
【Day17】自訂元件(1)
下一篇
【Day19】React Native設計模式(1)
系列文
React Native的學習與實作30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言