React Native 最佳实践
无论你是 React Native 开发者新手还是经验丰富的开发者,你都必须意识到代码实践是一项不可或缺的技能。作为一名开发者,交付项目是必须的,但编写可扩展且高质量的代码将对您和您的团队的未来发展大有裨益。
在我们继续之前,这些实践可以在 React Native CLI 或 Expo 项目上进行。根据 RN 团队的说法,从 2024 年起,Expo 将成为构建 React Native 项目的官方框架。
在本篇博文中,我们将学习 React Native 项目的代码实践。记住,一个好的项目需要平衡以下几点:
-
可扩展
-
一致性
-
可维护
-
可读性
阅读我的博客,了解如何以 ReactJS 开发人员的身份开始使用 React Native 开发人员
1.项目结构
开发人员的首要任务是拥有一个可维护、可读且可扩展的代码库。您的项目结构也会对未来的开发人员有所帮助。使用 Expo,您可以掌握项目的结构,但作为一名 React Native 开发人员,您应该根据自己的项目情况规划项目结构:
my-app/
├── assets/
│ ├── fonts/
│ ├── images/
│ └── icons/
├── components/
│ ├── Button.js
│ ├── Button.styles.js
│ └── Header.js
├── screens/
│ ├── HomeScreen/
│ │ ├── HomeScreen.js
│ │ └── HomeScreen.styles.js
│ └── ProfileScreen/
│ ├── ProfileScreen.js
│ └── ProfileScreen.styles.js
├── navigation/
│ ├── AppNavigator.js
│ ├── AuthNavigator.js
│ └── MainNavigator.js
├── redux/ (or store/ if using Zustand, MobX, etc.)
│ ├── actions/
│ ├── reducers/
│ ├── store.js
│ └── types.js
├── services/
│ ├── api.js
│ └── auth.js
├── utils/
│ ├── helpers.js
│ └── constants.js
├── App.js
├── package.json
├── .babelrc
└── README.md
更新:请记住,根据你的需求,探索特定领域或功能的架构。感谢B Camphart和Idris Gadi
2. 导入别名
过长的导入路径会使代码更难阅读和维护。与其使用像 这样的长相对路径../../../components/Button
,不如使用别名来缩短它们,提高代码的可读性。
import Button from 'components/ui/Button';
import Header from 'components/layout/Header';
3. 进口订单
为了自动管理导入的顺序,你可以为 Babel 配置一个插件来帮你处理。这样可以保持导入的整洁,并减少手动干预。
npm install --save-dev babel-plugin-module-resolver
4. TypeScript
在 TypeScript (TS) 和 JavaScript (JS) 之间进行选择时,几乎没有争议,尤其是在大型应用程序中。TypeScript 提供静态类型检查,有助于在编译时而不是运行时捕获错误,从而生成更可靠、更易于维护的代码。
5.风格
有多种方法可以为 RN 项目设置样式。您可以使用 NativeWind,也可以通过 React Native 进行样式设置。面对如此众多的选择,我们应该选择一致性、可扩展性和可维护性。点击此处阅读我关于样式设置的博客
1. 内联:对于大型项目来说,这根本不是一个好方法。
<View style={{ backgroundColor: 'blue', padding: 10 }}>
<Text style={{ color: 'white' }}>Hello</Text>
</View>
2. StyleSheet API:很好,但样式不可重用
import { StyleSheet, View, Text } from 'react-native';
const styles = StyleSheet.create({
container: {
backgroundColor: 'blue',
padding: 10,
},
text: {
color: 'white',
},
});
const App = () => (
<View style={styles.container}>
<Text style={styles.text}>Hello</Text>
</View>
);
3. 独立样式:这是我在大型项目中偏爱的样式设置方式。创建一个独立的样式style.js
,并在需要的组件中使用它。
/components
├── MyComponent.js
├── MyComponent.styles.js
/App.js
// MyComponent.styles.js
import { StyleSheet } from 'react-native';
export default StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#f5f5f5',
},
title: {
fontSize: 24,
fontWeight: 'bold',
color: '#333',
marginBottom: 20,
},
button: {
backgroundColor: '#007bff',
paddingVertical: 10,
paddingHorizontal: 20,
borderRadius: 5,
},
buttonText: {
color: '#fff',
fontSize: 16,
fontWeight: '600',
},
});
// MyComponent.js
import React from 'react';
import { View, Text, Pressable } from 'react-native';
import styles from './MyComponent.styles';
const MyComponent = () => {
return (
<View style={styles.container}>
<Text style={styles.title}>Hello from MyComponent</Text>
<Pressable style={styles.button}>
<Text style={styles.buttonText}>Click Me</Text>
</Pressable>
</View>
);
};
export default MyComponent;
4. 样式化组件:大型项目的另一种方式。
更新:请检查一下
显然,Styled Components 存在性能问题:https://github.com/styled-components/styled-components/issues/3940
import styled from 'styled-components/native';
const Container = styled.View`
background-color: blue;
padding: 10px;
`;
const StyledText = styled.Text`
color: white;
`;
const App = () => (
<Container>
<StyledText>Hello</StyledText>
</Container>
);
5. Native Wind: NativeWind 是设计应用样式的好方法。安装 Native Wind 后,您可以使用这些类来设计应用样式。这样,您就可以委托他人进行样式设计工作。
import React from 'react';
import { View, Text, Pressable } from 'react-native';
import { styled } from 'nativewind';
const App = () => {
return (
<View className="flex-1 justify-center items-center bg-gray-100">
<Text className="text-2xl font-bold text-blue-500 mb-4">
Welcome to NativeWind!
</Text>
<Pressable className="bg-blue-500 px-4 py-2 rounded">
<Text className="text-white font-semibold">Press Me</Text>
</Pressable>
</View>
);
};
export default App;
6.道具
在 React Native 中,props 用于组件间通信,允许数据从父组件流向子组件。与样式一样,管理 props 的方法有很多种。一致性至关重要,因此建议在整个项目中坚持使用一种方法。
此外,为了使代码更简洁易读,请务必解构 props。解构不仅可以提高代码的可读性,还能更容易地识别组件正在使用的 props。
const MyComponent = ({ title, subtitle }) => {
return (
<View>
<Text>{title}</Text>
<Text>{subtitle}</Text>
</View>
);
};
7. 状态管理
高效的状态管理能够确保应用在代码库增长时依然保持高性能和可管理性。如今,我们有很多选择来选择最佳的状态管理方案。
a. 优先考虑本地状态而不是全局状态
b.Context API
用于简单状态
c. 使用状态管理库来管理复杂状态
d. 不可变状态更新
e. 优先redux toolkit
于redux
import { createSlice } from '@reduxjs/toolkit';
const booksSlice = createSlice({
name: 'books',
initialState: [],
reducers: {
addBook: (state, action) => {
state.push(action.payload);
},
removeBook: (state, action) => {
return state.filter(book => book.id !== action.payload);
},
},
});
export const { addBook, removeBook } = booksSlice.actions;
export default booksSlice.reducer;
8.崩溃分析
为了确保应用程序的健康并减少崩溃,实施崩溃分析和错误跟踪非常重要:
a. 使用崩溃分析工具:实现类似以下服务 -Firebase Crashlytics
或Sentry
b. 测试应用的稳定性
运行自动化测试和手动压力测试,以发现极端情况下的崩溃。利用 TestFlight 或 Google Play Beta 测试等服务。
您可以跟踪原生崩溃(iOS/Android)和 JavaScript 错误。使用 ErrorBoundary 捕获 JavaScript 错误并将其记录到崩溃分析服务中。
c. 跟踪 JS 和原生错误
import React from 'react';
import * as Sentry from '@sentry/react-native';
class ErrorBoundary extends React.Component {
componentDidCatch(error, errorInfo) {
Sentry.captureException(error, { extra: errorInfo });
}
render() {
if (this.state.hasError) {
return <Text>Something went wrong.</Text>;
}
return this.props.children;
}
}
9. 日志记录
日志记录有助于跟踪应用程序行为、调试问题和收集分析数据。
a. 使用日志框架
-
React Native Logger:专为 React Native 设计的易于使用的记录器。
-
Winston:一个可以与 React Native 和 Node.js 一起使用的多传输日志库。
import logger from 'react-native-logger';
logger.log('This is a debug log');
logger.warn('This is a warning log');
logger.error('This is an error log');
b. 区分日志级别
-
使用适当的日志级别
debug
,如info
、、warn
和error
。 -
在生产中,仅允许错误和警告日志,以最大限度地减少日志记录的详细程度,而在开发模式下,使用调试和信息。
远程日志记录
考虑将日志发送到远程日志服务,例如:
-
纸迹
-
洛格利
-
Firebase 分析
d. 谨慎记录敏感信息
避免记录敏感的用户信息,如密码、令牌或个人数据。
10.测试
每个项目的测试都至关重要。作为开发人员,质量是开发人员的责任。在 React Native 世界中,有:
-
单元测试
-
集成测试
-
端到端测试
至少花时间进行端到端测试。有很多工具可用于测试。
学习愉快!在Twitter上跟我打招呼
文章来源:https://dev.to/hellonehha/react-native-code-practices-6dl