改进 React 和 JS 代码的 5 个技巧
两周前,我开始了一个新项目,里面已经写了一些代码。然而,没有任何最佳实践可供遵循。开始一个新项目时,重要的是要聚在一起,明确团队需要遵循的基础原则和最佳实践/指南,以编写出最佳代码:可维护、可读、易于理解。
我将描述我在项目中看到的 5 种场景以及如何改进它们。
关键词是:一致性
1. 导入模块的顺序
以有组织的方式安排您的 ES6 模块将节省您查找任何缺失/不需要的模块的时间。
前
import { DatePicker } from '../../components'
import axios from 'axios'
import { IUser } from '../../models/User'
import React from 'react'
import { toCamelCase } from '../utils'
import { Button } from '@material-ui/core'
后
// node_modules
import React from 'react'
import { Button } from '@material-ui/core'
import axios from 'axios'
// Local modules
import { DatePicker } from '../../components'
import { toCamelCase } from '../utils'
// Types + Interfaces
import { IUser } from '../../models/User'
在Before 版本中,我们可以看到包是无序的,对于单个文件来说可能没什么问题,但当你打开大量文件并试图查找特定的包时,就很难了。团队已经达成共识,将导入内容按After版本分组,每个模块之间用空行分隔。由于文件保持一致,因此可以删除注释。
2. 尽可能使用解构
另一个重要的事情是避免不必要的嵌套和重复。在大多数情况下,这将大大提高可读性。
前
const UserProfile = props => (<div>
<span>{props.firstName}</span>
<span>{props.lastName}</span>
<img src={props.profilePhoto}/>
</div>)
后
const UserProfile = ({ firstName, lastName, profilePhoto }) =>
(<div>
<span>{firstName}</span>
<span>{lastName}</span>
<img src={profilePhoto}/>
</div>)
3. 变量和方法的命名约定
关于代码,重要的是要知道方法将返回什么,或者仅通过变量名称就可以轻松读取变量代表什么,例如:
前
let User = {}
User.car = true
User.admin = true
function NewUser() {
return User
}
function add_photo(photo) {
user.photo = photo
}
后
let user = {}
user.hasCar = true
user.isAdmin = true
function getUser() {
return user
}
function setUserPhoto(photoUrl) {
user.photoUrl = photoUrl
}
在After 中,我们保持变量和方法命名方式的一致性,保持一致:
- 对于布尔值使用:is、has、should前缀
- 对于方法,如果用于 props,请使用 get/set 前缀
- 方法和变量总体使用驼峰命名法
4. 让你的组件准备好常见的 props
前
const UserProfile = props => {
const { firstName, lastName, profilePhoto } = props
return (<div>
<span>{firstName}</span>
<span>{lastName}</span>
<img src={profilePhoto}/>
</div>)
}
后
const UserProfile = props => {
const { firstName, lastName, profilePhoto, ...rest} = props
return (<div {...rest}>
<span>{firstName}</span>
<span>{lastName}</span>
<img src={profilePhoto}/>
</div>)
}
在After中,组件准备注入常见的 React 属性,例如:style、className、key 等。使用扩展运算符,您可以将所有常见的 props 分组并将它们传递给容器。
5. 真正愚蠢的组件会让你的生活更轻松
创建哑组件并遵循单一责任原则允许您以简单的方式创建和贡献并保持干净的代码库。
前:
import axios from 'axios'
const UserProfile = props => {
const [user, setUser] = React.useState(null);
React.useEffect(() => {
getUser();
}, []);
async function getUser() {
try {
const user = await axios.get('/user/25')
} catch(error) {
console.error(error)
}
if(user.country === "DE") {
user.flag = "/de-flag.png"
} else if(user.country === "MX") {
user.flag = "/mx-flag.png"
}
setUser(user);
}
const { firstName, lastName, profilePhoto, userFlag} = user
return (<div>
<span>{firstName}</span>
<span>{lastName}</span>
<img src={profilePhoto}/>
<img src={userFlag}>
</div>)
}
后:
哪些方面会导致问题?
在组件内部添加业务逻辑 (BL) 会使维护、调试和测试变得困难。我建议将组件保留为展示组件。这样可以隔离业务逻辑,并专注于独立测试该部分。以前,所有功能都是混杂的。现在,我们已将各项职责分离,这使得测试和调试更加轻松。
// UserProfilePage.jsx
// Does everything related to the UserProfilePage, adding any additional props or BL
import { fetchUser } from '../api'
const UserProfilePage = props => {
const [user, setUser] = React.useState(null);
React.useEffect(() => {
getUser();
}, []);
async function getUser() {
const user = fetchUser(error => console.error(error))
if(user.country === "DE") {
user.flag = "/de-flag.png"
} else if(user.country === "MX") {
user.flag = "/mx-flag.png"
}
setUser(user);
}
return <UserProfile {...user}/>
}
// API.js
// Fetches the data and handles errors on that. That's it
export const fetchUser = async (errorHandler) => {
try {
const user = await axios.get('/user/25')
} catch(error) {
errorHandler(error)
}
}
// UserProfile.jsx
// Displays the UserProfile and that's it
const UserProfile = props => {
const { firstName, lastName, profilePhoto, ...rest} = props
return (<div {...rest}>
<span>{firstName}</span>
<span>{lastName}</span>
<img src={profilePhoto}/>
</div>)
}
奖励:如果您正在使用类型检查器,请使其有效。
如果您的团队选择使用类型检查器,那么严格地使用它来确保它能够覆盖并服务于决定使用它的目的就非常重要。
前:
const UserProfile = (props: any) => {
const { firstName, lastName, profilePhoto, shouldShowPhoto } = props
return (<div>
<span>{firstName}</span>
<span>{lastName}</span>
<img src={profilePhoto}/>
</div>)
}
后:
interface IUserProfile {
firstName: string
lastName: string
profilePhoto: string
shouldShowPhoto?: boolean
}
const UserProfile = (props: IUserProfile) => {
const { firstName, lastName, profilePhoto, shouldShowPhoto } = props
return (<div>
<span>{firstName}</span>
<span>{lastName}</span>
{shouldShowPhoto && <img src={profilePhoto}/>}
</div>)
}
我并不是说这些规则适用于所有项目,但你的团队应该能够定义它们并达成一致。
您使用哪些最佳实践/指南?
文章来源:https://dev.to/adancarrasco/5-tips-to-improve-your-react-and-js-code-32g7