大家好,我是桃翁,一個不止前端的前端工程師。
眾所周知, React 是一個 JavaScript 庫,它是當今最流行和行業(yè)領先的前端開發(fā)庫。
JavaScript 是一種松散的類型化語言,因此,它捕獲了運行時。這樣做的結果就是 JavaScript 錯誤被捕獲得非常晚,這可能導致嚴重的 bug。
當然 React 作為一個 JavaScript 庫,也繼承了這個問題。
干凈代碼(Clean code)[1]是一種一致的編程風格,它使代碼更容易編寫、讀取和維護。任何人都可以編寫計算機可以理解的代碼,但是優(yōu)秀的開發(fā)人員可以編寫人類可以理解的干凈的代碼。
干凈的代碼是一種以讀者為中心的開發(fā)風格,它提高了我們的軟件質(zhì)量和可維護性。
編寫干凈代碼需要編寫具有清晰和簡單的設計模式的代碼,這使得人們可以輕松地閱讀、測試和維護代碼。因此,干凈的代碼可以降低軟件開發(fā)的成本。這是因為編寫干凈的代碼所涉及的原則,消除了技術債務。
在本文中,我們將介紹一些在使用 React 和 TypeScript 時使用的有用模式。
為了讓您的團隊更容易地保持代碼健康并優(yōu)先處理技術債務工作,請嘗試使用 Stepsize 的 VS Code[2] 和 JetBrains[3] 擴展。它們幫助工程師創(chuàng)建技術問題,將它們添加到迭代 中,并持續(xù)解決技術債務——而不離開編輯器。
現(xiàn)在讓我們來了解一下在使用 React 和 Typescript 時應用的 10 個有用模式:
1、使用默認導入來導入 React考慮下面的代碼:
import * as React from "react";
雖然上面的代碼可以工作,但是如果我們不使用 React 的所有內(nèi)容,那么導入它們是令人困惑的,也不是一個好的做法。一個更好的模式是使用如下所示的默認導出:
import React, {useContext, useState} from "react";
使用這種方法,我們可以從 React 模塊中解構我們需要的東西,而不是導入所有的內(nèi)容。
注意: 要使用這個選項,我們需要配置 tsconfig.json 文件,如下所示:
{ "compilerOptions": { "esModuleInterop": true" } }
在上面的代碼中,通過將 esModuleInterop 設置為 true,我們啟用了 allowSyntheticDefaultImports [4] ,這對于 TypeScript 支持我們的語法非常重要。
2、 類型聲明要在運行時實現(xiàn)之前考慮下面的代碼:
import React, {Component} from "react"; const initialState = { count: 1 } const defaultProps = { name: "John Doe" } type State = typeof initialState; type Props = { count?: number } & typeof defaultProps class Counter extends Component { static defaultProps = defaultProps; state = initialState; // ... }
如果我們將運行時聲明和編譯時聲明分開,并且編譯時聲明在運行時聲明之前,那么上面的代碼可以更清晰、更易讀。
考慮下面的代碼:
import React, {Component} from "react"; type State = typeof initialState; type Props = { count?: number } & typeof defaultProps const initialState = { count: 1 } const defaultProps = { name: "John Doe" } class Counter extends Component { static defaultProps = defaultProps; state = initialState; // ... }
現(xiàn)在,初看起來,開發(fā)人員知道組件 API 是什么樣的,因為代碼的第一行清楚地顯示了這一點。
此外,我們還將編譯時聲明與運行時聲明分開。
3、給 children 提供明確的 props
Typescript 反映了 React 如何處理 children props,方法是在 react.d.ts 中為函數(shù)組件和類組件將其注釋為可選的。
因此,我們需要明確地為 children 提供一個 props 類型。但是,最好總是用類型明確地注釋children的 props。在我們希望使用 children 進行內(nèi)容投影的情況下,這是非常有用的,如果我們的組件不使用它,我們可以簡單地使用 never 類型來注釋它。
考慮下面的代碼:
import React, {Component} from "react"; // Card.tsx type Props = { children: React.ReactNode } class Card extends Component<Props> { render() { const {children} = this.props; return <div>{children}div>; } }
下面是一些注釋 children 的 props 類型:
- ReactNode | ReactChild | ReactElement。
- 對于原始類型可以使用:string | number | boolean。
- 對象和數(shù)組也是有效的類型。
- never | null | undefined – 注意:不建議使用 null 和 undefined。
4、 使用類型推斷來定義組件狀態(tài)或 DefaultProps
看下面的代碼:
import React, {Component} from "react"; type State = { count: number }; type Props = { someProps: string & DefaultProps; } type DefaultProps = { name: string } class Counter extends Component<Props, State> { static defaultProps: DefaultProps = {name: "John Doe"} state = {count: 0} // ... }
雖然上面的代碼可以工作,但是我們可以對它進行以下改進: 啟用 TypeScript 的類型系統(tǒng)來正確推斷readonly 類型,比如 DefaultProps 和 initialState。
為了防止由于意外設置狀態(tài)而導致的開發(fā)錯誤: this.state = {}。
考慮下面的代碼:
import React, {Component} from "react"; const initialState = Object.freeze({ count: 0 }) const defaultProps = Object.freeze({name: "John Doe"}) type State = typeof initialState; type Props = { someProps: string } & typeof defaultProps; class Counter extends Component<Props, State> { static readonly defaultProps = defaultProps; readonly state = {count: 0} // ... }
在上面的代碼中,通過凍結 DefaultProps 和 initialState,TypeScript 類型系統(tǒng)現(xiàn)在可以將它們推斷為readonly類型。
另外,通過在類中將靜態(tài) defaultProps 和狀態(tài)標記為 readonly,我們消除了上面提到的設置狀態(tài)引起運行時錯誤的可能性。
5、 聲明 Props/State 時使用類型別名(type),而不是接口(interface)
雖然可以使用interface,但為了一致性和清晰性起見,最好使用 type,因為有些情況下interface不能工作。例如,在前面的示例中,我們重構了代碼,以使 TypeScript 的類型系統(tǒng)能夠通過從實現(xiàn)中定義狀態(tài)類型來正確推斷 readonly類型。我們不能像下面的代碼那樣使用這個模式的interface:
// works type State = typeof initialState; type Props = { someProps: string } & typeof defaultProps; // throws error interface State = typeof initialState; interface Props = { someProps: string } & typeof defaultProps;
此外,我們不能用聯(lián)合和交集創(chuàng)建的類型擴展interface,因此在這些情況下,我們必須使用 type。
6、不要再 interface/type 中使用方法聲明
這可以確保我們的代碼中的模式一致性,因為 type/interface 推斷的所有成員都是以相同的方式聲明的。另外,--strictFunctionTypes 僅在比較函數(shù)時工作,而不適用于方法。你可以從這個 TS 問題中得到進一步的解釋。
// Don't do interface Counter { start(count:number) : string reset(): void } // Do interface Counter { start: (count:number) => string reset: () => string }
7、 不要使用 FunctionComponent
或者簡稱為 FC 來定義一個函數(shù)組件。
當使用 Typescript 和 React 時,函數(shù)組件可以通過兩種方式編寫:
像一個正常函數(shù)一樣,如下面的代碼:
type Props = { message: string }; const Greeting = ({ message }: Props) => <div>{message}div>;
使用 React.FC 或者 React.FunctionComponent,像下面這樣:
import React, {FC} from "react"; type Props = { message: string }; const Greeting: FC<Props> = (props) => <div>{props}div>;
使用 FC 提供了一些優(yōu)勢,例如對諸如 displayName、 propTypes 和 defaultProps 等靜態(tài)屬性進行類型檢查和自動完成。但是它有一個已知的問題,那就是破壞 defaultProps 和其他屬性: propTypes,contextTypes,displayName。
FC 還提供了一個隱式類型的 children 屬性,也有已知的問題。此外,正如前面討論的,組件 API 應該是顯式的,所以一個隱式類型的 children 屬性不是最好的。
8、 不要對類組件使用構造函數(shù)
有了新的 類屬性[5] 提議,就不再需要在 JavaScript 類中使用構造函數(shù)了。使用構造函數(shù)涉及調(diào)用 super ()和傳遞 props,這就引入了不必要的樣板和復雜性。
我們可以編寫更簡潔、更易于維護的 React class 組件,使用類字段,如下所示:
// Don't do type State = {count: number} type Props = {} class Counter extends Component<Props, State> { constructor(props:Props){ super(props); this.state = {count: 0} } } // Do type State = {count: number} type Props = {} class Counter extends Component<Props, State> { state = {count: 0} }
在上面的代碼中,我們看到使用類屬性涉及的樣板文件較少,因此我們不必處理 this 變量。
9、 不要在類中使用 public 關鍵字
考慮下面的代碼:
import { Component } from "react" class Friends extends Component { public fetchFriends () {} public render () { return // jsx blob } }
由于類中的所有成員在默認情況下和運行時都是 public 的,因此不需要通過顯式使用 public 關鍵字來添加額外的樣板文件。相反,使用下面的模式:
import { Component } from "react" class Friends extends Component { fetchFriends () {} render () { return // jsx blob } }
10、 不要在組件類中使用 private
考慮下面的代碼:
import {Component} from "react" class Friends extends Component { private fetchProfileByID () {} render () { return // jsx blob } }
在上面的代碼中,private 只在編譯時將 fetchProfileByID 方法私有化,因為它只是一個 Typescript 模擬。但是,在運行時,fetchProfileByID 方法仍然是公共的。
有不同的方法使 JavaScript 類的屬性/方法私有化,使用下劃線(_)變數(shù)命名原則如下:
import {Component} from "react" class Friends extends Component { _fetchProfileByID () {} render () { return // jsx blob } }
雖然這并沒有真正使 fetchProfileByID 方法成為私有方法,但它很好地向其他開發(fā)人員傳達了我們的意圖,即指定的方法應該被視為私有方法。其他技術包括使用 WeakMap、Symbol 和限定作用域的變量。
但是有了新的 ECMAScript 類字段的提議,我們可以通過使用私有字段輕松優(yōu)雅地實現(xiàn)這一點,如下所示:
import {Component} from "react" class Friends extends Component { #fetchProfileByID () {} render () { return // jsx blob } }
而且 TypeScript 支持 3.8 及以上版本私有字段的新 JavaScript 語法。
附加:不要使用 enum
盡管 enum 在 JavaScript 中是一個保留字,但是使用 enum 并不是一個標準的慣用 JavaScript 模式。
但是如果你使用的是 c # 或者 JAVA 這樣的語言,那么使用 enum 可能是非常誘人的。但是,還有更好的模式,比如使用編譯類型文字,如下所示:
// Don't do this enum Response { Successful, Failed, Pending } function fetchData (status: Response): void => { // some code. } // Do this type Response = Sucessful | Failed | Pending function fetchData (status: Response): void => { // some code. }
總結
毫無疑問,使用 Typescript 會給你的代碼增加很多額外的樣板文件,但是這樣做的好處是非常值得的。
為了使您的代碼更干凈、更好,不要忘記實現(xiàn)一個健壯的 TODO/issue [6]過程。它將幫助您的工程團隊獲得技術債務的可見性,在代碼庫問題上進行協(xié)作,并更好地規(guī)劃沖刺。
本文譯自:https://dev.to/alexomeyer/10-must-know-patterns-for-writing-clean-code-with-react-and-typescript-1m0g。
參考資料
[1]干凈代碼(Clean code):
https://gist.github.com/wojteklu/73c6914cc446146b8b533c0988cf8d29。
[2]Stepsize 的 VS Code:
https://marketplace.visualstudio.com/items?itemName=Stepsize.stepsize。
[3]JetBrains:
https://www.stepsize.com/r/jetbrains。
[4]allowSyntheticDefaultImports :
http://allowSyntheticDefaultImports。
[5]類屬性:
https://github.com/tc39/proposal-class-fields#consensus-in-tc39。
[6]TODO/issue :
https://www.stepsize.com/?utm_source=dev.to&utm_medium=referral&utm_campaign=patterns。
原文地址:https://mp.weixin.qq.com/s/ZgsbW8hNUgtStbSlIkw95A