as

Settings
Sign out
Notifications
Alexa
亚马逊应用商店
AWS
文档
Support
Contact Us
My Cases
新手入门
设计和开发
应用发布
参考
支持

轻量级重构

轻量级重构

在开始之前,让我们通过优化导入来进行一些轻量级重构。在第1部分中,当我们需要组件和屏幕时在单独的行上导入它们。随着我们应用的发展,可能会有许多导入语句,导致代码读取不便。

为了减少导入语句的数量,我们可以在每个文件夹中创建一个index.ts文件,以便在文件夹中列出了组件/屏幕。它会将每个组件/屏幕列出为命名导出,可以将其在一行上导入。这与我们从'react-native'导入组件(例如View和Text)时使用的语法相同(例如,import { View, Text } from 'react-native')。

将索引文件添加到Components文件夹

首先,我们将为components文件夹创建一个index.ts

  • components文件夹中,创建一个名为index.ts的新文件。我们使用.ts扩展名,因为这是一个纯TypeScript文件,不包含任何JSX。
src/
├── components/
   ├── Header.tsx
   ├── VideoCard.tsx
|   └── index.ts
└── App.tsx
  • 打开index.ts并为components文件夹中的每个组件添加导入语句。
  • 添加列出每个组件的导出语句。

index.ts文件应如下所示:

已复制到剪贴板。

import Header from './Header';
import VideoCard from './VideoCard';

export {
    Header,
    VideoCard
}

导入组件

接下来,我们需要更新LandingScreen.tsx以使用新的导入方法。

  • LandingScreen.tsx中,删除Header和VideoCard的导入语句。
  • 添加一条导入语句,该语句添加来自index.ts的组件。请注意,我们只需要指定从components文件夹进行导入,因为将在该文件夹中读取index.ts文件以找到命名导出(Header、VideoCard)。

LandingScreen.tsx中的导入语句应如下所示:

已复制到剪贴板。

import React, {useState, useEffect} from 'react';
import {FlatList, StyleSheet, View} from 'react-native';
import {Header, VideoCard} from '../components';

将索引文件添加到screens文件夹

现在,我们将对screens文件夹重复上述过程。

  • screens文件夹中创建一个名为index.ts的文件。
src/
├── screens/
│   ├── LandingScreen.tsx
|   └── index.ts
└── App.tsx
  • 打开index.ts并为screens文件夹中的每个组件添加导入语句。
  • 添加列出每个组件的导出语句。

index.ts文件应如下所示:

已复制到剪贴板。

import LandingScreen from './LandingScreen';

export {
    LandingScreen,
}

导入屏幕

现在我们需要更新App.tsx中的导入语句。

  • 打开App.tsx
  • 删除LandingScreen的导入语句。
  • 添加一条导入语句,该语句用于从screens文件夹中添加LandingScreen屏幕。

App.tsx中的导入语句现在应该如下所示:

已复制到剪贴板。

import * as React from 'react';
import {LandingScreen} from './screens';
  • 重新加载应用并验证所有内容的呈现效果是否相同。

这种重构可能看起来幅度不大,但是当您构建包含许多组件和屏幕的复杂应用时,它将有助于减少每个文件顶部的导入语句的数量。