🔍 搜尋結果:for

🔍 搜尋結果:for

寫 React 時必備的幾個 VS Code Extensions:新手推薦

來看看一些對 React 開發人員最有用的 VS Code 外掛吧! - 原文網址:https://dev.to/devland/vs-code-extensions-you-should-use-as-a-react-developer-2f6i ## ES7 React/Redux/GraphQL/React-Native snippets ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qoxlb7rz6gzkx906xfr5.jpg) 最流行的外掛之一,由 React 開發人員提供,也由 React-Native 開發人員參與。它帶有許多速記前綴,您可以輕鬆使用它來加快開發過程。 這個外掛提供了很多你可能不知道的功能。一旦你安裝了這個驚人的外掛,創建一個新文件並輸入 rfce 然後按回車鍵,這將生成一個 React 功能組件,導入 React 並導出元件。 ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8m942g0szndpv3bwprrb.jpg) 它還允許您在幾秒鐘內創建不同的 es7 片段,只需輸入前綴簡寫並按 enter。 此外,如果您使用的是 Redux 或 GraphQL,此外掛也為它們提供了程式碼片段。 ## VSCode React Refactor ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aa1etaf6lasubpmsjxgf.jpg) 簡單,但非常有用。允許您將 JSX 部分提取到新元件、文件等。使用類別、函數和箭頭函數並支持 TypeScript 和 TSX。 ## Prettier ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7tddr5birva6pja6ygoa.jpg) 經過多年使用 Prettier,我認為它是任何專案的都好用的外掛。這是一個自動為你格式化程式碼的工具。它有助於保持程式庫的一致性,因為無論團隊中的開發人員有什麼個人偏好,所有程式碼都將以相同的方式格式化。 ## Eslint ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6l039819s4qx6ngf0e8i.jpg) 用於查找程式碼中的錯誤和缺陷。它可以幫助開發人員編寫沒有錯誤和警告的優質程式碼。 此外,它可以自動修復錯誤和警告。 ## Stylelint ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ufskyyg4id7ets3rcjnt.jpg) 和ESLint類似,也是一個linter,但是針對樣式。它可以檢測並突出顯示不正確的樣式,並有助於保持樣式一致和有序。更重要的是,它適用於純 CSS 以及 SCSS 和 LESS 等預處理器。 ## GitLens ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6wmh3we9qrykvxari4mo.jpg) 增強了 Visual Studio Code 中內置的 Git 功能。它可以幫助您通過 Git 責備註釋和 code lens 一目了然地可視化代碼作者身份,無縫導航和探索 Git 存儲庫。 ## Git History ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzsboqxicv3bs8f0n7p1.jpg) 允許您查看 git 日誌和文件歷史記錄,並比較分支或提交。 ## Settings sync ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iphz26rbvb85pnuzcijf.jpg) 您是否曾經重新安裝作業系統或更改您編寫程式碼的設備、繼續安裝 VS Code、然後發現您需要重新安裝所有外掛?它可以自動保存你的外掛和 VS Code 設置,然後在另一台設備上安裝和配置它們。 ## Bracket Pair Colorization Toggler ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4xw0embc8ohxzmaw54fq.jpg) 非常簡單但有用的擴展。突出顯示匹配的括號對。 ## Auto Close Tag ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yda8pr1303sn1kdzwoz8.jpg) 一個簡單但最有用的 React 外掛之一。它所做的是一件非常簡單的事情。 Auto close tag,顧名思義,為元素創建一個結束標籤,這意味著開發人員不需要編寫結束標籤。這可能看起來很簡單,但實際上,自動關閉標籤非常有用。 ## Auto Rename Tag ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7kjq4bz8u1ccgxgk2w9t.jpg) 自動重命名成對的 HTML/XML 標籤。 ## Auto Import ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zy56itc3bb5jvecscf2v.jpg) 自動為所有可用導入查找、解析並提供代碼操作和代碼完成。適用於 TypeScript 和 TSX。 ## Import Cost ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4wxw0io8difxgthdan5c.jpg) 在 React 中,安裝和導入套件是非常常見和必要的。導入大量套件可能會導致性能問題,因為其中一些包可能很重。此外掛在編輯器中顯示套件的大小。 ## Jumpy ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cp8cldekpyxyesyz1o8j.jpg) 您通常如何從一行程式碼轉到幾行和空格之外的特定關鍵字?多次使用鍵盤箭頭或單擊滑鼠?使用 Jumpy,您可以更有效率,因為它可以讓您快速跳轉到特定單詞。 ## i18n Ally ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jmqx39hkds4lbeoytb1p.jpg) 如果您的應用程序支持多種語言,就非常好用。 Formatting toggle ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fhhj774y6xeapll2tomq.jpg) 在某些情況下,我們希望暫時禁用像 Prettier 這樣的代碼格式化程序。這可以通過 Formatting toggle 外掛來完成,無需修改編輯器設置。 ## Npm intellisense ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/75wl3nmlkporzfsnxl6g.jpg) 為導入語句中的 npm 模塊提供自動完成功能。 ## Web Accessibility ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i3lni8zqwdh4ngwyk1rm.jpg) 用於提高 Web 應用程序可訪問性的出色插件。它突出顯示了您應該考慮更改的元素,還提供了有關如何更新它們的提示。 ## Live Share ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/74okun8atu01lphpjo7c.jpg) 您願意與其他人協作編寫您的代碼嗎? 此外掛使您能夠與他人實時編輯和調試代碼。 ## Better comments ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/odj7yo1a5sntmhkl4x57.jpg) 用於在您的代碼中創建更人性化的註釋。它可以將評論分類為警報、查詢、待辦事項和突出顯示,並以不同的顏色顯示它們。 ## Docker ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/patpizcxw2hs6gu823em.jpg) 如果您的應用程序是使用 Docker 部署的,您可以考慮使用來簡化構建、管理和部署來自 VS Code 的容器化應用程序。 ## Remote — SSH ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kk6amn6yubsmio7uen68.jpg) 您是否需要訪問服務器才能遠程編輯文件?遠程 SSH 讓您可以使用任何帶有 SSH 服務器的遠程機器作為您的開發環境。您可以輕鬆地在遠程和本地開發環境之間切換。 ## WSL ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2kd4n337eomix1ba0tn7.jpg) 如果您更喜歡在 Linux 上開發您的應用程序,但您的主要操作系統是 Windows,您可以考慮使用 Windows 子系統 Linux (WSL)。如果這樣做,那麼您可能會發現 WSL 擴展很有用,因為它可以讓您在 Windows 上使用 Vs Code構建 Linux 應用程序。在使用基於 Linux 的工具、運行時和實用程序進行開發時,您可以獲得 Windows 的所有生產力。 ## 實時服務器 ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rzaylae1618ndvty1agf.jpg) 如果您需要在文件更改時通過實時瀏覽器重新加載來快速啟動實時服務器,很推薦。 ## Debugger for Chrome and Debugger for Firefox ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5hqzk58hdihl2syoctg5.jpg) 調試器提供了許多有用的功能,例如在斷點處暫停代碼執行、變量檢查等。這些擴展提供了 VS Code 編輯器內部的調試功能。 ## Change-case ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qeoqoevy2a6d646ht1ir.jpg) 顧名思義,此擴展允許您更改當前選擇或當前單詞的大小寫。如果您有很長的文本或想將多個變量轉換為相同的大小寫,這將非常有用。 ## Regex Previewer ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pr4eesyhl5bpj0afhhll.jpg) 大多數開發人員很少編寫 Regex 表達式。但是,如果必須,此擴展可能會非常方便。它在並排文檔中顯示當前正則表達式的匹配項。 ## DotENV ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/19cpgt5rvygiysu87qi8.jpg) _.env_ 文件的語法突出顯示。 ## 結論 希望對您有幫助!

德國資深架構師:給新手工程師的幾點建議

一名資深的德國軟體架構師 Jeroen De Dauw,寫了一篇很好的文章,給新手工程師一些寫程式的建議。 - 原文出處:https://dev.to/jeroendedauw/advice-for-junior-developers-30am --- ## 給新手工程師的一般建議 ### 1. 程式碼不是重點 作為開發者,我們喜歡寫程式。大多數工程師希望收到的任務明確,可以不用管技術之外的事情,專心解決有趣的技術挑戰。 請花足夠的心力去確認,您正在解決正確的問題。引用管理學大師 Peter Drucker 的話:高效率地去做一件根本沒必要的事情,結果依然是完全沒意義。儘早、經常去搜集回饋,透過「持續交付」來向真正的用戶互動,成為敏捷(Agile)的工程師。 軟體開發成本高昂,現實世界專案的絕大部份工作都是在維護而已。再加上目標應該是對用戶、對生意有幫助,所以結論就是:寫程式最好的方法,經常是完全不寫。引用比爾蓋茲的話:用程式碼有幾行來衡量工程進度,就像用重量來衡量飛機的製造進度。 另請參閱:YAGNI 原則、KISS 原則、The Last Responsible Moment 文章。 ### 2. 軟體設計很重要 在我開發生涯的前五年,我以為軟體設計是架構師或其他特殊職位的人在做的事。我以為開發者專注在完成任務即可,以為軟體設計、最佳實踐、寫測試這些,都不關我的事。我的程式能跑,我的生產力很高,我以為這樣就對了。 直到我閱讀了 Robert C. Martin 的 Clean Code,這書刺激了我對軟體設計的關注,並包含許多範例與啟發。其中最啟發我的是:走得快的唯一方法,就是走得好。也就是說,如果你把事情搞得一團糟,結果只會讓你速度更慢。 學習寫出設計良好的乾淨程式碼,需要時間和精力。而且剛開始的時候,會寫比較慢,並且會犯錯誤。 ### 3. 使用最佳實踐 寫測試通常會有幫助。雖有例外,但大多數時候,寫自動化測試會大有幫助。寫測試就是一種最佳實踐。 如果你不太會寫測試,請遵循最佳實踐並為所有內容寫測試。**開始時,盲目遵循最佳實踐比遵循自己弱弱的判斷要好**。一段時間之後,您將知道怎麼寫測試比較有效,並能夠區分您搞砸了和不值得編寫測試的情況。因為 bug 變少了、重構起來更輕鬆了,您將開始理解測試帶來的深入的價值。**到有了自己的判斷力後,您將能夠超越最佳實踐**。 此建議適用於您在學習任何最佳實踐的新手時期。自動化測試只是一個例子。 有個陷阱要注意,明智的最佳實踐,與荒謬、適得其反的做法之間,只有一線之隔。因為大多數程式碼都很亂,而且大多數開發者(包括資深人員)不了解軟體設計的基礎知識,因此事情就更複雜了。有一個好的指導者很重要。除此之外,根據我自己的經驗,要小心只存在您的語言、框架社群的最佳實踐。尋找那些已經存在了幾十年的長青建議比較好。 --- ## 給新手工程師的技術建議 ### 4. 寫測試 寫自動化測試。也許在寫程式之前先寫測試,例如運用測試驅動開發(TDD)。這讓您可以輕鬆反覆驗證幾段程式是否正確,而不用一直手動跑測試、除錯。 > 你覺得先寫測試很煩嗎?但之後再忙著抓 bug 有比較好? 更重要的是,測試為您重構時提供了額外保障。你需要持續重構來保持程式乾淨。沒有可靠的測試保障,程式碼就可能越變越亂。 如果您的程式碼設計不佳,例如使用繼承進行重用,或使用靜態函數,則編寫測試會很困難。另一方面,如果您有遵循 SOLID 原則、沒有全局依賴項,那麼寫出好的測試並不困難。 設計好測試也很重要,因為糟糕的測試只會拖慢開發速度。避免將測試綁定到被測程式碼的實作細節或系統結構。 ### 5. 不要用繼承來做到程式碼重用 這是讓人以為是最佳實踐的其中一個反例。我的建議是:剛開始時,根本就不要用繼承來做到程式碼重用。這通常都幫助有限,而且帶來一大堆麻煩。請多用組合、少用繼承(關鍵字:composition over inheritance)。 ### 6. 寫出 OOP 程式碼 學習 SOLID 原則,避免寫出 STUPID 原則的程式碼 ( https://williamdurand.fr/2013/07/30/from-stupid-to-solid-code/ )。理解這些原則和反模式非常有價值。 創造一些真正的物件。只有靜態方法的類別,根本不算是物件導向。盡量避免完全使用靜態寫法。 ### 7. 寫出函數式程式碼 不要把函數式程式設計,跟指令式程式設計搞混了。 重點不是完全切換到函數式語言。而是學習使用函數式風格的優點。例如減少狀態、讓函數專心一件事。另請參閱:https://www.destroyallsoftware.com/screencasts/catalog/functional-core-imperative-shell ### 8. 程式碼稍微重複沒關係 將一大塊程式碼到處複製貼上當然很不好。有尊嚴的開發者很快就發現這一點,並開始遵循某種形式的:不重複自己原則 Don't Repeat Yourself (DRY)。不幸的是,對 DRY 的追求往往會導致過度工程和額外的複雜性。所以會有一條新原則:寫兩次原則 Write Everything Twice(WET)。也就是僅在第三次出現重複時,才動手改善重複段落。 ### 9. 型別、命名、註解 試著寫一些能夠表達自我的程式碼,避免寫註解。 > 每次寫註解時,都應該要皺一下眉頭,感受到自己的表達能力有點失敗。 —— Robert C. Martin 註解很危險,因為有可能說謊。程式碼可以不更新註解就修改,那一開始的註解就變錯誤了。這種情況下,註解不但沒幫助,還會誤導到別人。 要寫出能夠表達自我的程式碼: - **一個函數只做一件事** 因為只做一件事,就能給一個清楚的命名。 - **減少狀態** - **使用型別** 定義清楚的型別,加上跑測試,能讓系統更穩定。 - **減少混合型別** 避免可以同時是整數、布林值或字串的參數或回傳值。如果讓每個函數專心一件事,這自然會做到。 - **寫測試** 良好的全面測試,也同時會是程式碼的使用說明範例。 Robert C. Martin 的書 Clean Code 在命名和寫註解方面有提供一些很好的經驗法則。 --- 以上,希望對大家有幫助!

在 React 中使用 Design Patterns:以 Strategy Pattern 舉例

在 React 前端開發時,常常會需要在不同的元件、hook、utils 中寫一些邏輯。 有些時候,使用策略模式會很有幫助,這篇文章給您參考。 - 原文出處:https://dev.to/itshugo/applying-design-patterns-in-react-strategy-pattern-enn ## 出問題了:霰彈槍手術(Shotgun Surgery) Shotgun Surgery 是一種程式寫很爛的信號。想對程式規格做一點小修改,需要改一大堆地方。 ![](https://refactoring.guru/images/refactoring/content/smells/shotgun-surgery-01-2x.png) 在專案中通常如何發生?假設我們需要為產品寫一個報價卡片,我們根據客戶所在國家,調整價格、貨幣、折扣方式和文字說明: ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5iz9oso7ozaqm0qibd76.png) 大多數工程師可能會這樣寫: - 元件:`PricingCard`、`PricingHeader`、`PricingBody`。 - Utility functions:`getDiscountMessage`(在 **utils/discount.ts** 中),`formatPriceByCurrency`(在 **utils/price.ts** 中)。 - `PricingBody` 元件會計算最終價格。 完整程式碼範例:https://codesandbox.io/s/react-strategy-pattern-problem-h59r02?from-embed 現在假設我們需要更改一個國家/地區的定價計劃,或為另一個國家/地區添加新的定價計劃。您將如何處理這段修改?您必須至少修改 3 個地方,並向已經滿亂的 `if-else` 區塊添加更多條件: - 修改 `PricingBody` 組件。 - 修改 `getDiscountMessage` 函數。 - 修改 `formatPriceByCurrency` 函數。 如果您聽說過 S.O.L.I.D 原則,我們已經違反了前 2 條原則:單一職責原則和開閉原則。 ## 解決方法:策略模式 策略模式非常簡單。我們可以簡單的理解為,每個國家的定價方案都是一個策略。在那個策略類別中,會實現該策略的所有相關邏輯。 假設您熟悉 OOP,我們可以有一個實現共享/公共邏輯的抽像類別(`PriceStrategy`),然後具有不同邏輯的策略將繼承該抽像類別。 `PriceStrategy` 抽像類別如下所示: ``` import { Country, Currency } from '../../types'; abstract class PriceStrategy { protected country: Country = Country.AMERICA; protected currency: Currency = Currency.USD; protected discountRatio = 0; getCountry(): Country { return this.country; } formatPrice(price: number): string { return [this.currency, price.toLocaleString()].join(''); } getDiscountAmount(price: number): number { return price * this.discountRatio; } getFinalPrice(price: number): number { return price - this.getDiscountAmount(price); } shouldDiscount(): boolean { return this.discountRatio > 0; } getDiscountMessage(price: number): string { const formattedDiscountAmount = this.formatPrice( this.getDiscountAmount(price) ); return `It's lucky that you come from ${this.country}, because we're running a program that discounts the price by ${formattedDiscountAmount}.`; } } export default PriceStrategy; ``` 我們只需將實例化的策略作為 prop 傳遞給 PricingCard 元件: ``` <PricingCard price={7669} strategy={new JapanPriceStrategy()} /> ``` `PricingCard` 的 props 定義為: ``` interface PricingCardProps { price: number; strategy: PriceStrategy; } ``` 同樣,如果您了解 OOP,那麼我們不僅在使用繼承,而且還在此處使用多態性(Polymorphism)。 完整程式碼範例:https://codesandbox.io/s/react-strategy-pattern-solution-mm0cvm?from-embed 使用這個解決方案,我們只需要添加一個新的策略類別,而不需要修改任何現有程式碼。這樣,我們也滿足了 S.O.L.I.D 原則。 ## 結論 因為我們在 React 程式碼中檢測到程式碼發臭:Shotgun Surgery,所以我們使用了策略模式來解決它。 ### Before ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7wn31uolfo6xfy3mh8fo.png) ### After ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xheeb2splcwj2kkqwsfo.png) 現在邏輯都存在一個地方,不再分佈在許多地方。 --- 以上是 Strategy Pattern 的簡單說明,希望對您有幫助。

36 個免費、漂亮的 React UI 模板與主題套件

網路上免費的 React 版型資源不太好找,最好有一份懶人包。 這份列表整理了各式各樣的模板與主題套件,希望對您有幫助。 - 原文出處:https://dev.to/davidepacilio/35-free-react-templates-and-themes-32ci --- ##1. Open ![](https://dev-to-uploads.s3.amazonaws.com/i/gy9nddokri1vobwrtbna.jpg) [**Live demo**](https://open.cruip.com/) / [**Download**](https://github.com/cruip/open-react-template) Open 是一個免費的 React 模板,專為開源專案、線上服務、數位產品,創建快速、專業的登陸頁面而生。為了吸引潛在客戶和電子郵件訂閱者,Open 提供了一個多功能的資源庫,其中包含時尚、簡約和可重複使用的元件和元素。 --- ##2. Atomize ![](https://dev-to-uploads.s3.amazonaws.com/i/ks2st96gb0tbu1ybuy6k.jpg) [**Live demo**](https://atomizecode.com/) / [**Download**](https://github.com/proksh/atomize) Atomize 是一個 React UI 框架,旨在幫助開發人員與設計師合作,輕鬆構建一致和諧的用戶界面。由於樣式指南和靈活網格等資源的完美結合,Atomize 適合建立任何類型的響應式網站。 --- ##3. Treact ![](https://dev-to-uploads.s3.amazonaws.com/i/3aw9a273jibs97o2l09m.jpg) [**Live demo**](https://treact.owaiskhan.me/) / [**Download**](https://gumroad.com/l/QaruQ) Treact 是使用 TailwindCSS 作為前端框架開發的現代 React 模板和 UI 組件展示庫。這個精美的檔案庫提供了 7 個內建的主頁、8 個輔助頁面以及 52 個預先設計的元素和段落。每個內容都可以針對家用電腦、平板電腦和移動設備進行擴充。 --- ##4. MatX ![](https://dev-to-uploads.s3.amazonaws.com/i/q99tvy2uvyvol2xet2et.jpg) [**Live demo**](http://matx-react.ui-lib.com/dashboard/analytics) / [**Download**](https://ui-lib.com/downloads/matx-react-dashboard/) MatX 是一個建立在 Material Design 之上的精美 React Native 模板。此模板使用 React、Redux 和 Material UI,它包含為 Web 應用程式提供新造型可能需要的所有基本功能。 MatX 的免費版本可用於輕鬆設置管理面板、用戶管理系統和專案管理系統。 --- ##5. Holly ![](https://dev-to-uploads.s3.amazonaws.com/i/dcrv1qxgo3rgq9a3j3at.jpg) [**Live demo**](https://lukemcdonald.github.io/holly-react/) / [**Download**](https://github.com/lukemcdonald/holly-react) Holly 是一個響應式 React JS 模板,適用於線上服務和數位產品的生產者,能在主要產品仍在開發中時,就開始搜集電子郵件地址。這個模板最初是由 [Cruip](https://cruip.com/) 用 HTML 設計的,然後在這個版本中用 React 撰寫。 --- ##6. OAH-Admin ![](https://dev-to-uploads.s3.amazonaws.com/i/rteeixluj4n09a3s69ma.jpg) [**Live demo**](https://oah-admin.ahmedelywa.com/extra-components/progress/) / [**Download**](https://github.com/AhmedElywa/oah-admin) OAH-Admin 是一個基於 Gatsby 的免費 React 管理儀表板模板,帶有 oah-ui 元件和元素包。這個 React 模板有良好的 UI 元件色調,超級整潔和靈活的格式使任何人都可以輕鬆建立 SaaS 應用程式、管理面板、儀表板。 --- ##7. Gatsby Starter Ghost ![](https://dev-to-uploads.s3.amazonaws.com/i/ocey043yzsdt31f7yi9s.jpg) [**Live demo**](https://gatsby.ghost.org/) / [**Download**](https://github.com/TryGhost/gatsby-starter-ghost) 使用 Ghost 這個基於 Gatsby 的入門模板,輕鬆建立高效能網站。Gatsby Starter Ghost 是一個乾淨而現代的模板,適用於部落格、雜誌或任何新聞網站。該產品專門設計來幫助任何人在網路上建立個人空間並分享想法、創意和更新。 --- ##8. Star Admin ![](https://dev-to-uploads.s3.amazonaws.com/i/hlbf4y4pl4a5od2c8chb.jpg) [**Live demo**](https://www.bootstrapdash.com/demo/star-admin-free/react/template/demo_1/preview/dashboard) / [**Download**](https://github.com/BootstrapDash/StarAdmin-Free-React-Admin-Template) 一個免費的 React Native 模板,提供了無窮無盡的各種基本元素,可以將任何想法變為現實。該模板具有精心製作的儀表板,包含大量整齊排列和組織的元件,它可以完美地與所有最新和現代的瀏覽器配合使用,並且能夠使資料可視化過程更易於管理。 --- ##9. Carolina Admin Dashboard ![](https://dev-to-uploads.s3.amazonaws.com/i/05r7fsc1jzylez5diu6f.jpg) [**Live demo**](https://demo.uifort.com/carolina-react-admin-dashboard-material-ui-free-demo/LandingPage) / [**Download**](https://uifort.com/template/carolina-react-admin-dashboard-material-ui-free/) 如果您正在尋找一個令人驚嘆且實用的 React 儀表板模板,Carolina Admin Dashboard 擁有啟動和運行您 Web 專案所需的一切。這個漂亮的模板建立在 Material-UI 框架之上,採用乾淨清新的設計,遵循所有 Google 的 Material Design 指南。此外,核心結構是完全響應式和開源的。 --- ##10. Tabler ![](https://dev-to-uploads.s3.amazonaws.com/i/nu5vq6j5buk36iz8prsn.jpg) [**Live demo**](http://tabler-react.com/) / [**Download**](https://github.com/tabler/tabler-react) Tabler 是一個免費的 React 管理儀表板模板,非常適合任何類型的後端 Web 應用。此管理模板包含大量精心設計的範例,無需從頭開始,可為您節省大量時間,它還附帶可重複使用的元件,例如按鈕、地圖、圖表、表單等。 --- ##11. React Nice Resume ![](https://dev-to-uploads.s3.amazonaws.com/i/ci5hhvp6ki5o3mpk8zbz.jpg) [**Live demo**](https://nordicgiant2.github.io/react-nice-resume-page/#home) / [**Download**](https://github.com/nordicgiant2/react-nice-resume) React Nice Resume 是一個漂亮的主題,如果您是開發人員、設計師或一般的數位創作者,可以用來宣傳您自己和您的作品。該資源展示了一個獨特的主頁,帶有粒子背景、工作經驗時間線、技能圖表、顯示最新專案的縮略圖、一個帶有功能輸入表單的段落。 --- ##12. Boss Lite ![](https://dev-to-uploads.s3.amazonaws.com/i/zq92otm0bc9t3mwinkxb.jpg) [**Live demo**](http://boss.ux-maestro.com/app/tables/data-table) / [**Download**](https://github.com/ilhammeidi/boss-lite) Boss Lite 是一個基於 React 和 Redux 的管理儀表板模板。此模板為您帶來清新現代的設計和多種配色方案。它支援大多類型的 Web 專案,並且 Flexbox 佈局而變得很流暢。 --- ##13. Chakra UI ![](https://dev-to-uploads.s3.amazonaws.com/i/poootemj2t5caoi4lryt.jpg) [**Live demo**](https://chakra-ui.com/) / [**Download**](https://github.com/chakra-ui/chakra-ui/) Chakra UI 提供了一組好用、可重用的 React 功能元件,使建立好用網站和用戶界面變得非常簡單。 Chakra UI 中的幾乎所有元素都兼容深色模式,它們遵循 WAI-ARIA 指南規範,並構建在 React UI Primitive 之上以實現無限的可組合性。 --- ##14. Black Dashboard React ![](https://dev-to-uploads.s3.amazonaws.com/i/2r1tx4uxug6k1xlnr3pr.jpg) [**Live demo**](https://demos.creative-tim.com/black-dashboard-react/#/admin/dashboard) / [**Download**](https://www.creative-tim.com/product/black-dashboard-react) Black Dashboard React 是用於管理界面的 React 模板。該模板基於 Bootstrap 建立的設計指南,是基於企業的應用程式,是強大後端軟體可用的優秀前端選項。它具有更高等級的切分、設計套件、可重複使用的圖表,能夠不斷改善用戶和開發體驗。 --- ##15. Argon Design System ![](https://dev-to-uploads.s3.amazonaws.com/i/tvrfqzddf6kwmhiwje6x.jpg) [**Live demo**](https://demos.creative-tim.com/argon-design-system-react/) / [**Download**](https://github.com/creativetimofficial/argon-design-system-react) 使用 Bootstrap 4 和 Reactstrap 的 React 設計系統。Argon Design System 帶有 100 多個單獨的元件、內建的範例,並且每個元素都有多種樣式、懸停、焦點狀態,任何人都可以輕鬆使用。該產品是從原型設計到正式上線的完美解決方案。 --- ##16. Devias Kit - Admin Dashboard ![](https://dev-to-uploads.s3.amazonaws.com/i/j7lqqfvgmujtgg1m80oi.jpg) [**Live demo**](https://react-material-dashboard.devias.io/dashboard) / [**Download**](https://github.com/devias-io/react-material-dashboard) Devias Kit 是一個響應式 Material Design 管理儀表板,專為 React 使用 Google 自己的 Material Design 框架建立。可以自定義設置、指令、圖標和樣式。該模板包含清晰直觀的目錄和文件、快速入門文件,如果您想對設計進行任何更改,甚至還有 Sketch 文件。 --- ##17. Dev Blog ![](https://dev-to-uploads.s3.amazonaws.com/i/1tym4ekzrftd6ldcflid.jpg) [**Live demo**](https://ryanfitzgerald.github.io/devblog/) / [**Download**](https://github.com/RyanFitzgerald/devblog) Dev Blog 是一個 React 網站模板,專為快速建立副專案和產品而生。該網站模板帶有一個首頁,其中顯示了部落格名稱、社交媒體圖示以及帶有文字和圖像的文章縮圖。該模板還包括單個文章頁面,有漂亮且精心策劃的排版。 --- ##18. Material PRO ![](https://dev-to-uploads.s3.amazonaws.com/i/scakf4swq5j99hln1xqx.jpg) [**Live demo**](https://wrappixel.com/demos/free-admin-templates/materialpro-reactadmin-lite/main/#/starter/starter) / [**Download**](https://www.wrappixel.com/templates/materialpro-react-admin-lite/) Material Pro 是一個免費的 React Native 模板,為任何需要管理儀表板的人精心製作。這個漂亮而清爽的產品採用模組化和現代設計理念開發,100% 免費使用和下載,並包含許多頁面,可幫助您更快、更輕鬆地建立專案。 --- ##19. Ant Design Landing ![](https://dev-to-uploads.s3.amazonaws.com/i/wnld469wyg4u9pfk31i1.jpg) [**Live demo**](https://landing.ant.design/) / [**Download**](https://github.com/ant-design/ant-design-landing) Landing 是 Ant Design System 建立的模板。內涵不同樣式的首頁和內頁模組。 --- ##20. Isomorphic ![](https://dev-to-uploads.s3.amazonaws.com/i/zy0at5stk267a06n5f95.jpg) [**Live demo**](https://isomorphic.redq.io/dashboard) / [**Download**](https://github.com/pujoey/ismorphic) Isomorphic 是一個易於管理且有吸引力的管理模板,具有大量靈活的元件。 --- ##21. Shards Dashboard Lite ![](https://dev-to-uploads.s3.amazonaws.com/i/71cn55agi3k9er11xk4o.jpg) [**Live demo**](https://designrevision.com/demo/shards-dashboard-lite-react/blog-overview) / [**Download**](https://designrevision.com/downloads/shards-dashboard-lite-react/) Shards 是一個免費的 React 儀表板模板,具有現代設計系統和許多自定義頁面和部分。 --- ##22. uiw ![](https://dev-to-uploads.s3.amazonaws.com/i/e6aakqf9m9g67mstwvi9.jpg) [**Live demo**](https://uiwjs.github.io/) / [**Download**](https://github.com/uiwjs/uiw) uiw 是用於 React 16+ 的高質量 React 元件庫和 UI 工具包。 --- ##23. React Material Admin ![](https://dev-to-uploads.s3.amazonaws.com/i/te6tezfjcp008lb4q7du.jpg) [**Live demo**](https://flatlogic.github.io/react-material-admin/#/login) / [**Download**](https://flatlogic.com/templates/react-material-admin) React Material Admin 是一個建立在 Material-UI 框架之上的 React 儀表板。 --- ##24. Material KIT React ![](https://dev-to-uploads.s3.amazonaws.com/i/cq2xlu4tci8km6p2tia7.jpg) [**Live demo**](https://demos.creative-tim.com/material-kit-react/) / [**Download**](https://www.creative-tim.com/product/material-kit-react) Material UI KIT 是一款免費的 React UI 主題,其設計靈感來自 Google 的 Material Design,設計清新整潔。 --- ##25. Airframe ![](https://dev-to-uploads.s3.amazonaws.com/i/qwt4nv73xjn14a9g09yl.jpg) [**Live demo**](http://dashboards.webkom.co/react/airframe/dashboards/projects/) / [**Download**](https://github.com/0wczar/airframe-react) Airframe 是一個基於 Bootstrap 4 和 React 16 的免費開源 React 應用程式模板。 --- ##26. Gatsby Simplefolio ![](https://dev-to-uploads.s3.amazonaws.com/i/pe3clc53zqsntgh3vw3n.jpg) [**Live demo**](https://gatsby-simplefolio.netlify.app/) / [**Download**](https://github.com/cobidev/gatsby-simplefolio) Gatsby Simplefolio 是一個乾淨、美觀且響應迅速的 React 組合模板。 --- ##27. Ant Design Pro ![](https://dev-to-uploads.s3.amazonaws.com/i/diktnddjjf630tdyyqa8.jpg) [**Live demo**](https://pro.ant.design/) / [**Download**](https://github.com/ant-design/ant-design-pro/) React --- ##28. React SaaS Template ![](https://dev-to-uploads.s3.amazonaws.com/i/yiq5ast9jw3knt8l92l0.jpg) [**Live demo**](https://reactsaastemplate.com/) / [**Download**](https://github.com/dunky11/react-saas-template) --- ##29. Shards React ![](https://dev-to-uploads.s3.amazonaws.com/i/34zfg3e4qbbzklmgr4uh.jpg) [**Live demo**](https://designrevision.com/downloads/shards-react/) / [**Download**](https://github.com/designrevision/shards-react) --- ##30. Base Web ![](https://dev-to-uploads.s3.amazonaws.com/i/8q3bxpsll7k0qrhzdlmj.jpg) [**Live demo**](https://baseweb.design/) / [**Download**](https://github.com/uber/baseweb) --- ##31. Light Blue React Dashboard ![](https://dev-to-uploads.s3.amazonaws.com/i/tfwzjgvh2sa8e5v9a0oa.jpg) [**Live demo**](https://demo.flatlogic.com/light-blue-react/#/app/main/dashboard) / [**Download**](https://github.com/flatlogic/light-blue-react-template) --- ##32. React JS Landing ![](https://dev-to-uploads.s3.amazonaws.com/i/ibuom994cxj3pzb2yzoz.jpg) [**Live demo**](https://react-landing-page-template.herokuapp.com/#page-top) / [**Download**](https://github.com/IssaafKattan/React-Landing-Page-Template) --- ##33. Admin Pro ![](https://dev-to-uploads.s3.amazonaws.com/i/0f1pjehgesa25ts39wx7.jpg) [**Live demo**](https://wrappixel.com/demos/free-admin-templates/adminpro-react-lite/main/#/dashboard) / [**Download**](https://www.wrappixel.com/templates/adminpro-react-admin-lite/#comparison) --- ##34. Blueprint ![](https://dev-to-uploads.s3.amazonaws.com/i/d1owpo8lfg3zfq1p2vpx.jpg) [**Live demo**](https://blueprintjs.com/) / [**Download**](https://github.com/palantir/blueprint) --- ##35. Datta ![](https://dev-to-uploads.s3.amazonaws.com/i/3con3tndvc7au5zg1jb0.jpg) [**Live demo**](http://lite.codedthemes.com/datta-able/react/default/dashboard/default) / [**Download**](https://codedthemes.com/item/datta-able-react-free-admin-template/) --- ##36. Flatlogic One ![](https://dev-to-uploads.s3.amazonaws.com/i/63flhvqcbh7jtfvih9do.jpg) [**Live demo**](https://flatlogic.github.io/one-react-template/#/login) / [**Download**](https://flatlogic.com/templates/one-free-react-template) --- ##結論 我希望這組免費的 React 模板和主題能夠幫助您!

都要 2023 年了還在用 console.log 嗎?來看看 10 個 console 進階用法!

寫 JavaScript 時,仍在使用 console.log 來除錯抓蟲? 是時候**升級你的技能**並學習 JavaScript console 物件的全部功能了。 從 console.table 到 console.time,這些進階方法和技巧將改善您 **debug 訊息的品質和可讀性**,讓您更輕鬆地故障排除和修復問題。 在 2023 年成為 JavaScript 除錯高手吧! - 原文出處:https://dev.to/naubit/why-using-just-consolelog-in-2023-is-a-big-no-no-2429 ## 😞 問題 僅使用 console.log 的最大問題之一是,它會使程式碼混亂且難以閱讀。此外,它本身的資訊量不是很大。它只是輸出你傳遞給它的任何內容的值,沒有任何上下文或其他資訊。 所以,這裡有十個你應該知道的 JavaScript console 物件方法和技巧,值得了解一下! ## 1️⃣ console.table 此方法以可讀且易於理解的格式,輸出資料表格。console.table 不是只顯示陣列或物件,而是以表格格式顯示,使它更易於瀏覽和理解。 ``` // Output an array of objects as a table const users = [ { id: 1, name: 'John Doe' }, { id: 2, name: 'Jane Doe' } ]; console.table(users); ``` 這將以表格格式輸出 users 陣列,每個物件的屬性作為列,物件作為行。 ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hek6gxo4x73b6mvmlawr.png) ## 2️⃣console.group console.group 和 console.groupEnd。這些方法可以在控制台中,創建嵌套的可摺疊資料組。**這對於組織和構建 debug 訊息非常有用**,讓您可以輕鬆查看程式碼不同級別發生的情況。 ``` console.group('User Details'); console.log('Name: John Doe'); console.log('Age: 32'); console.groupEnd(); ``` 這將在 console 中創建一個嵌套的、可摺疊的資料組,標題為“使用者詳細資訊”。組內的日誌消息將縮進並分組在一起。 ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8ybn1uwvyltjzxcaaytx.png) ## 3️⃣console.time console.time 和 console.timeEnd 可以測量執行程式碼所需的時間。這對於識別程式中的性能瓶頸、效能優化非常有用。 ``` console.time('Fetching data'); fetch('https://reqres.in/api/users') .then(response => response.json()) .then(data => { console.timeEnd('Fetching data'); // Process the data }); ``` 這將測量「從特定 URL 獲取資料並解析 JSON 回應」所需的時間。耗用時間會在控制台中輸出。 ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f3hdvnz2of3an1a21j3c.png) ## 4️⃣console.assert 此方法允許您在程式碼中寫 assertions,這些是應該始終為 true 的語句。如果 assertions 失敗,console.assert 將在控制台中輸出錯誤消息。**這對於除錯抓蟲、確保程式碼正常運作非常有用。 ``` function add(a, b) { return a + b; } // Test the add function const result = add(2, 3); console.assert(result === 5, 'Expected 2 + 3 = 5'); ``` 如果 add 函數在給定輸入 2 和 3 時未返回預期結果 5,就在控制台中輸出錯誤訊息。 ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y25c157xwhasxnaiakd5.png) ## 5️⃣設置日誌樣式 使用 `console` 物件輸出樣式和顏色。 `console` 物件**允許您輸出不同顏色和樣式的文字**,使您的除錯輸出更具可讀性和更容易理解。 您可以在 console.log 語句中使用 %c 佔位符來指定輸出文字的 CSS 樣式。 ``` console.log('%cHello world!', 'color: red; font-weight: bold;'); ``` 這將輸出文字“Hello world!”,並使用指定的 CSS 樣式,以紅色和粗體顯示。 ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1p82u116icnlodu046nr.png) ## 6️⃣console.trace 使用 `console.trace` 方法輸出堆疊追踪(stack trace)。這對於理解程式碼中的執行流程、識別**特定日誌消息的來源非常有用。** ``` function foo() { console.trace(); } function bar() { foo(); } bar(); ``` 這將在控制台中輸出堆疊跟踪,顯示導致 `console.trace` 呼叫的函數呼叫序列。看起來像這樣: ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zx16nee1mp0avh04msri.png) ## 7️⃣console.dir 使用 `console.dir` 方法以分層格式輸出物件的屬性。這對於**探索物件的結構**、查看其屬性和方法非常有用。 ``` const obj = { id: 1, name: 'John Doe', address: { street: '123 Main St', city: 'New York', zip: 10001 } }; console.dir(obj); ``` 這將以分層格式輸出 `obj` 物件的屬性,允許您查看物件的結構及其所有屬性和值。 ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ihgkg5e4wxznpaqzb8jr.png) ## 8️⃣console.count 使用 `console.count` 方法計算特定日誌消息的輸出次數。這對於**追蹤特定程式碼路徑的執行次數**以及識別程式碼中的熱點很有用。 ``` function foo(x) { console.count(x); } foo('hello'); foo('world'); foo('hello'); ``` 這將在控制台中輸出字串“hello”,然後是數字 1。然後它將在控制台中輸出字串“world”,然後是數字 1。最後,它會再次輸出字符串“hello”,然後出書數字 2(因為它被呼叫了兩次)。 ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cx7n8aargexpq1pvqj6n.png) ## 9️⃣console.clear 使用 `console.clear` 方法清除控制台輸出。這能保持您的除錯輸出**有條理和整潔**,讓您更容易專注於您感興趣的訊息。 ``` console.log('Hello world!'); console.clear(); console.log('This log message will appear after the console is cleared.'); ``` 這將輸出字串 “Hello world!”,接著一個空行(因為控制台已清除)。然後它會輸出字串 “This log message will appear after the console is cleared.” ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ihzapi1gcin6gtqa600v.png) ## 1️⃣0️⃣console.profile 使用 `console.profile` 和 `console.profileEnd` 方法來衡量程式碼的性能。這對於**識別性能瓶頸和優化代碼**、提高速度和效率非常有用。 ``` console.profile('MyProfile'); // Run some code that you want to measure the performance of for (let i = 0; i < 100000; i++) { // Do something } console.profileEnd('MyProfile'); ``` 這將開始分析 `console.profile` 和 `console.profileEnd` 呼叫之間的程式碼,並在執行 `console.profileEnd` 時在控制台中輸出結果。輸出將包括有關執行所花費時間的詳細訊息、以及其他與性能相關的各種訊息。 ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wjw25tagjwdupmqxy1d5.png) ## 💭 最後的一些想法 在 2023 年,不要僅僅滿足於 `console.log` - JavaScript 控制台物件中有許多**更強大、更有價值的工具和技術。** 從 `console.table` 到 `console.time`,這些方法和技巧將幫助您提高除錯輸出的品質和可讀性,並使其**更容易排除和修復代碼中的問題**。 所以,為什麼不在 2023 年提高您的除錯技能並嘗試這些技術呢? 以上簡單分享,希望對您有幫助!

經驗分享:Code Review 程式碼審查的藝術

程式碼審查很難。以下是一些心得分享。 - 原文出處:https://dev.to/saminarp/today-i-learned-the-subtle-art-of-code-reviews-3pef --- 我最近在審查 https://github.com/humphd/my-photohub 的一個 PR。 這是我有生以來第一次進行程式碼審查,也讓我知道這項任務有多麼困難。第一次當審閱者,我發現自己盯著程式碼,思考可以做些什麼來讓它更好。感覺相當迷茫。我想出了一些平庸的建議。沒想到什麼厲害的。沒有什麼讓我覺得很滿意的建議。然後是 Dave 教授 https://github.com/humphd 對我正在審查的同一個 PR 進行程式碼審查。我只是坐在那裡,對他看到而我沒看到的細節感到驚訝。他提出了一些大改善,比如更好的程式設計邏輯,以及一些小建議,比如更新專案描述。這些小建議我也可以提出:更好的專案描述、更適合專案的圖示而不是預設的 React 圖示、並為某些事情創建紀錄追蹤。為什麼我會忽略掉 Dave 教授如此優雅、毫不費力就指出的明顯事情? ## 一些程式碼審查的最佳實踐 這是一篇很棒的文章 https://google.github.io/eng-practices/review/reviewer/looking-for.html 我在研究程式碼審查最佳實踐時找到的。 它漂亮地闡述了設計、功能、複雜性、測試、命名、註釋、樣式、一致性、文檔和上下文都是代碼審查的重要組成。 ## 時間、注意力、溝通 好的審查需要時間和注意力。它需要我們批判性地思考程式設計邏輯。對於初學者來說,盯著別人寫的程式碼來建議一些有意義的東西,可能會讓人感到不知所措。害怕犯錯。害怕冒犯寫程式的人。我知道,因為這些我都有感受到。在開源專案中,在提供建設性回饋的同時,在溝通中保持禮貌和尊重很重要。我們有時可能不認同審查,這種時候,我們應該禮貌地溝通。 在給予和接受回饋時,保持開放的心態也很重要。正是通過這種思想交流和回饋,我們才能夠隨著時間一直進步。 如果你有一些寫程式經驗,只要花足夠的時間專心看程式碼,幾乎總是可以提出改進建議。 ## 從小處著手 如果您是初學者,請從小處著手並向他人學習。閱讀 Dave 教授的評論,我學到了很多重要的東西。然後我意識到,只有看到更有經驗的人如何審查程式碼,我才能變得更好。我記下了我在 GitHub 上閱讀他的大量評論所學到的東西。我把這些東西變成了清單: - 如果不清楚,請詢問有關某程式碼的具體問題。 - 找找看未使用的依賴項和優化 package.json 的方法。 - 從整個程式碼庫的上下文中來看事情。 - 留下一些鼓勵的話,指出開發人員做對了什麼! - 專注於功能和相容性。 - 找出清晰的命名和適當的命名約定。 - 查看 README 檔或 CONTRIBUTING.md 檔時,請看看樣式、格式、拼寫和語法的一致性。 - 確保設計和UI看起來不錯。 - 確保單元測試是為這段程式碼適當設計的。 - 確保程式碼符合提供的某個樣式指南。 ## `linters` 會帶給我們信任 程式碼自動檢查器和靜態工具分析器可以幫助審閱者節省大量時間在尋找愚蠢的拼寫錯誤或樣式錯誤。linters 和 sanners 的作用大概就是拼寫和語法檢查。省下了檢查格式和其他風格的麻煩,審閱者可以專注於程式碼的實際邏輯。作為程式碼審閱者,必須使用可用的自動代碼檢查器來節省時間和心思。 ## 關於生產力的最後一點想法 如果你像我一樣喜歡閱讀有關心理學和生產力的文章,這是一篇很棒的文章 https://jamesclear.com/focus#Focus%20on%20the%20Process

7 個可以刺激網頁設計靈感的好地方:設計師、開發者推薦

身為開發者或設計師,要常常了解最新的設計趨勢,才能保持競爭力。 這邊有七個可以看到很多設計、刺激設計靈感的好地方,與您分享。 原文出處:https://dev.to/mohsenkamrani/7-websites-to-get-inspiration-for-next-level-web-design-1leg --- ## 1. https://dribbble.com 設計師社群分享網站。可以提供各種登陸頁面的設計靈感。 優點: 一個龐大而活躍的社群,大量設計可參考。 缺點:某些設計可能過於複雜或難以複製。 ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1670546361467/au1-ZogHe.png) ## 2. https://www.awwwards.com/ 展示來自世界各地的最佳設計,包括許多創意和有效的登錄頁面設計。 優點:高品質的設計,注重用戶體驗。 缺點:可能不像其他靈感來源那樣多樣化。 ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1670546444885/yExBAkGov.png) ## 3. https://www.behance.net/ 具有一系列設計組合,包括許多高品質登陸頁面的設計範例。 優點:含有大量設計稿,方便瀏覽和搜尋。 缺點:可能不像其他靈感來源那樣專注於登陸頁面。 ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1670546543511/RnNYQQKjG.png) ## 4. https://onepagelove.com/ 一個專門的網站,有很多啟發性的單頁設計,包括許多登陸頁面範例。 優點:專注於單頁設計,易於瀏覽和搜尋。 缺點:可能沒有其他靈感來源那麼多的多樣性。 ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1670546719953/9H4TBCmh8.png) ## 5. https://www.landingfolio.com/ 集合了網路上的最佳登陸頁面設計,為設計師提供豐富的靈感。 優點:大量高品質的設計,易於瀏覽和搜尋。 缺點:可能沒有其他靈感來源那麼多的多樣性。 ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1670546787563/o3nKNVT7C.png) ## 6. https://uxplanet.org/ 一個專注於使用者體驗設計的網站,包含許多精心設計的登錄頁面範例。 優點:注重用戶體驗,設計風格廣泛。 缺點:可能沒有其他靈感來源那麼多的設計。 ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1670546884319/oxqguR2Nz.png) ## 7. https://www.siteinspire.com/ 網頁設計靈感的精選集合,許多有效登錄頁面的範例。 優點:大量高品質的設計,易於瀏覽和搜尋。 缺點:可能沒有其他靈感來源那麼多的多樣性。 ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1670546938441/lXC_X5Dym.png) --- 希望您喜歡此清單,並使用它來為您的下一個專案獲得靈感。

寫出更好 JavaScript 的幾個實務技巧:新手推薦

JavaScript 寫起來有很大彈性,但如何改善自己的 JavaScript 品質呢?以下是一份實用的參考指南。 - 原文出處:https://dev.to/taillogs/practical-ways-to-write-better-javascript-26d4 # 使用 TypeScript 改善 JS 的第一個技巧就是,不要寫 JS。寫 TypeScript 吧。它是微軟寫的一個語言,算是 JS 的母集合(一般的 JS 可以直接在 TS 裡面跑)。TS 在 JS 之上添加了一個全面的型別系統。長期下來,整個前端生態系,幾乎都支援 TS 語言了。下面介紹一下 TS 的優點。 **TypeScript 可以確保「型別安全」** 型別安全代表編譯器驗證了所有型別是否以「合法」的方式被使用。換句話說,如果你創建一個接受「數字」的函數 `foo`: ``` function foo(someNum: number): number { return someNum + 5; } ``` 該「foo」函數呼叫時要傳一個數字: 正確用法 ``` console.log(foo(2)); // prints "7" ``` 錯誤用法 ``` console.log(foo("two")); // invalid TS code ``` 除了需要花時間加型別以外,沒有其他缺點了。好處則是顯而易見。型別安全針對常見錯誤提供了額外預防,這對於像 JS 這樣鬆散的語言來說,是一件好事。 **TypeScript 的型別系統,讓你能重構大型應用程式** 重構大型 JS 應用程式是一場噩夢。主要是因為它不會檢查函數簽名。也就是說,JS函數隨便呼叫,編譯器都不會先報錯。舉個例,如果我有一個函數「myAPI」,由 1000 個不同的服務使用: ``` function myAPI(someNum, someString) { if (someNum > 0) { leakCredentials(); } else { console.log(someString); } } ``` 我稍微更改了呼叫簽名: ``` function myAPI(someString, someNum) { if (someNum > 0) { leakCredentials(); } else { console.log(someString); } } ``` 我必須自已 100% 去確認,使用此功能的1000 個地方,都有正確更新用法。漏掉的地方,在執行時就會壞掉。在 TS 中相同的情境如下: before ``` function myAPITS(someNum: number, someString: string) { ... } ``` after ``` function myAPITS(someString: string, someNum: number) { ... } ``` 如您所見,「myAPITS」函數跟在 JavaScript 中一樣修改。但是,這段程式碼無法順利產出 JavaScript,而是會出現無效 TypeScript 的錯誤提示,因為用到它的1000個地方,現在型別就出錯了。正是因為「型別安全」,這 1000 個案例會阻止編譯。 **TypeScript 使團隊溝通架構更容易** 正確設定 TS 後,要先定義介面跟類型,不然很難寫程式碼。這也順便提供了一種簡潔、可溝通的架構提案方法。例如,如果我想跟後端提出新的「請求」類型,可以使用 TS 將以下內容提交給團隊。 ``` interface BasicRequest { body: Buffer; headers: { [header: string]: string | string[] | undefined; }; secret: Shhh; } ``` 雖然也是要寫一點程式碼,但可以先提供以上內容作為初步想法、取得回饋,而不用一次設計完功能。像這樣強迫開發者先定義介面跟 API,能讓程式碼品質更好。 總體而言,TS 已經發展成為一種成熟且更可預測的 vanilla JS 替代品。當然還是要熟 JS,但我現在大多數新專案都是直接寫 TS。 # 使用現代功能 JavaScript是世界上最流行的程式設計語言之一。你可能會以為這語言已經被百萬開發者摸透了,其實不是。很多新功能是近期才加上去的。 **`async` 與 `await`** 長期以來,非同步、事件驅動的 callback 是 JS 開發中不可避免的: 傳統 callback ``` makeHttpRequest('google.com', function (err, result) { if (err) { console.log('Oh boy, an error'); } else { console.log(result); } }); ``` 上述程式碼會有越寫越多層的問題。JS 添加了一個新概念叫 Promises,可以避免嵌套問題。 Promises ``` makeHttpRequest('google.com').then(function (result) { console.log(result); }).catch(function (err) { console.log('Oh boy, an error'); }); ``` 與 callback 相比,Promise 的最大優勢是可讀性和可鏈性。 雖然 Promise 很棒,但它們仍然有一些不足之處。寫起來感覺有點怪。為了解決這個問題,ECMAScript 委員會添加一種使用 promise 的新方法,`async` 和 `await`: `async` 與 `await` ``` try { const result = await makeHttpRequest('google.com'); console.log(result); } catch (err) { console.log('Oh boy, an error'); } ``` 需要注意的是,`await` 的內容必須先被宣告為 `async`: 以前面 makeHttpRequest 舉例 ``` async function makeHttpRequest(url) { // ... } ``` 也可以直接 `await` 一個 Promise,因為 `async` 函數實際上只是 Promise 比較花哨的包裝寫法。這也意味著,`async/await` 代碼和 Promise 代碼在功能上是等價的。因此,請大方使用 `async/await` 吧。 **`let` and `const`** 以前大家寫 JS 都只能用 `var`。`var` 的變數作用域有一些獨特規則,一直讓人很困惑。從 ES6 開始,有了 `const` 跟 `let` 可以替代使用,幾乎不用再寫 `var` 了。 至於何時要用 const 何時要用 let 呢?永遠從 const 先開始使用。const 因為不可修改、更可預期,會讓程式碼品質更好。使用 let 的場景比較少,我寫 const 的頻率比 let 高 20 倍左右。 **箭頭 `=>` 函數** 箭頭函數是在JS中宣告匿名函數的簡潔方法。通常作為 callback 或 event hook 傳遞。 傳統的匿名 function ``` someMethod(1, function () { // has no name console.log('called'); }); ``` 在大多數情況下,這種風格沒有任何“不對”。但它的變數作用域很“有趣”,常導致許多意想不到的錯誤。有了箭頭函數之後,就沒這問題了。 匿名箭頭函數 ``` someMethod(1, () => { // has no name console.log('called'); }); ``` 除了更簡潔之外,箭頭函數還具有更實用的變數範圍界定。箭頭函數從定義它們的作用域繼承「this」。 在某些情況下,箭頭函數甚至可以更簡潔: ``` const added = [0, 1, 2, 3, 4].map((item) => item + 1); console.log(added) // prints "[1, 2, 3, 4, 5]" ``` 箭頭函數可以包括隱式的「return」語句。就不用寫大括弧、分號。 不過,這跟“var”被完全取代不同。傳統匿名函數仍然有需要的地方,例如類別方法定義。話雖如此,如果你總是預設使用箭頭函數,程式碼錯誤會少很多。 **展開運算子 `...`** 提取一個物件的鍵/值對,並將它們添加為另一個物件的子物件,是一種很常見的場景。從歷史上看,有幾種方法可以實現,但通通都很笨拙: ``` const obj1 = { dog: 'woof' }; const obj2 = { cat: 'meow' }; const merged = Object.assign({}, obj1, obj2); console.log(merged) // prints { dog: 'woof', cat: 'meow' } ``` 這寫法以前很常見,也很囉唆。多虧了「展開運算子」,再也不需要那樣寫了: ``` const obj1 = { dog: 'woof' }; const obj2 = { cat: 'meow' }; console.log({ ...obj1, ...obj2 }); // prints { dog: 'woof', cat: 'meow' } ``` 最棒的是,與陣列也可無縫接軌: ``` const arr1 = [1, 2]; const arr2 = [3, 4]; console.log([ ...arr1, ...arr2 ]); // prints [1, 2, 3, 4] ``` 它可能不是近期 JS 中最重要的功能,但它是我的最愛之一。 **範本文字(範本字串)** 字串處理太常見了,程式語言要能處理範本字串,才夠好用。處理動態內容、多行文字時,都會需要它: ``` const name = 'Ryland'; const helloString = `Hello ${name}`; ``` 我認為程式碼不言自明。看起來好多了。 **物件解構** 物件解構是一種從資料集合(物件、陣列等)中提取值,而無需反覆運算數據或顯式訪問其鍵的方法: 老方法 ``` function animalParty(dogSound, catSound) {} const myDict = { dog: 'woof', cat: 'meow', }; animalParty(myDict.dog, myDict.cat); ``` 新方法 ``` function animalParty(dogSound, catSound) {} const myDict = { dog: 'woof', cat: 'meow', }; const { dog, cat } = myDict; animalParty(dog, cat); ``` 不只這樣。您還可以在函數的簽名中定義解構: 解構範例二 ``` function animalParty({ dog, cat }) {} const myDict = { dog: 'woof', cat: 'meow', }; animalParty(myDict); ``` 它也適用於陣列: 解構範例三 ``` [a, b] = [10, 20]; console.log(a); // prints 10 ``` --- 以上,希望對您有幫助!

快速複習 React 基本觀念&實務範例:推薦新手參考

React 作為一個強大的前端工具,有很多需要熟悉的基本觀念&語法。 這篇文章做一個快速的全面整理,方便工作時,可以隨時翻閱,希望您喜歡。 - 原文出處:https://dev.to/reedbarger/the-react-cheatsheet-for-2020-real-world-examples-4hgg ## 核心概念 ### 元素和 JSX - React 元素的基本語法 ``` // In a nutshell, JSX allows us to write HTML in our JS // JSX can use any valid html tags (i.e. div/span, h1-h6, form/input, etc) <div>Hello React</div> ``` - JSX 元素就是一段表達式 ``` // as an expression, JSX can be assigned to variables... const greeting = <div>Hello React</div>; const isNewToReact = true; // ... or can be displayed conditionally function sayGreeting() { if (isNewToReact) { // ... or returned from functions, etc. return greeting; // displays: Hello React } else { return <div>Hi again, React</div>; } } ``` - JSX 允許我們嵌套表達式 ``` const year = 2020; // we can insert primitive JS values in curly braces: {} const greeting = <div>Hello React in {year}</div>; // trying to insert objects will result in an error ``` - JSX 允許我們嵌套元素 ``` // to write JSX on multiple lines, wrap in parentheses: () const greeting = ( // div is the parent element <div> {/* h1 and p are child elements */} <h1>Hello!</h1> <p>Welcome to React</p> </div> ); // 'parents' and 'children' are how we describe JSX elements in relation // to one another, like we would talk about HTML elements ``` - HTML 和 JSX 的語法略有不同 ``` // Empty div is not <div></div> (HTML), but <div/> (JSX) <div/> // A single tag element like input is not <input> (HTML), but <input/> (JSX) <input name="email" /> // Attributes are written in camelcase for JSX (like JS variables <button className="submit-button">Submit</button> // not 'class' (HTML) ``` - 最基本的 React 應用程式需要三樣東西: - 1. ReactDOM.render() 渲染我們的應用程序 - 2. 一個 JSX 元素(在此情況下,稱為根節點) - 3. 一個用於掛載應用程式的 DOM 元素(通常是 index.html 文件中 id 為 root 的 div) ``` // imports needed if using NPM package; not if from CDN links import React from "react"; import ReactDOM from "react-dom"; const greeting = <h1>Hello React</h1>; // ReactDOM.render(root node, mounting point) ReactDOM.render(greeting, document.getElementById("root")); ``` ### 元件和 Props - 基本 React 元件的語法 ``` import React from "react"; // 1st component type: function component function Header() { // function components must be capitalized unlike normal JS functions // note the capitalized name here: 'Header' return <h1>Hello React</h1>; } // function components with arrow functions are also valid const Header = () => <h1>Hello React</h1>; // 2nd component type: class component // (classes are another type of function) class Header extends React.Component { // class components have more boilerplate (with extends and render method) render() { return <h1>Hello React</h1>; } } ``` - 如何使用元件 ``` // do we call these function components like normal functions? // No, to execute them and display the JSX they return... const Header = () => <h1>Hello React</h1>; // ...we use them as 'custom' JSX elements ReactDOM.render(<Header />, document.getElementById("root")); // renders: <h1>Hello React</h1> ``` - 元件可以在我們的應用程式中重複使用 ``` // for example, this Header component can be reused in any app page // this component shown for the '/' route function IndexPage() { return ( <div> <Header /> <Hero /> <Footer /> </div> ); } // shown for the '/about' route function AboutPage() { return ( <div> <Header /> <About /> <Testimonials /> <Footer /> </div> ); } ``` - 資料可以通過 props 動態傳遞給元件 ``` // What if we want to pass data to our component from a parent? // I.e. to pass a user's name to display in our Header? const username = "John"; // we add custom 'attributes' called props ReactDOM.render( <Header username={username} />, document.getElementById("root") ); // we called this prop 'username', but can use any valid JS identifier // props is the object that every component receives as an argument function Header(props) { // the props we make on the component (i.e. username) // become properties on the props object return <h1>Hello {props.username}</h1>; } ``` - Props 不可直接改變(mutate) ``` // Components must ideally be 'pure' functions. // That is, for every input, we be able to expect the same output // we cannot do the following with props: function Header(props) { // we cannot mutate the props object, we can only read from it props.username = "Doug"; return <h1>Hello {props.username}</h1>; } // But what if we want to modify a prop value that comes in? // That's where we would use state (see the useState section) ``` - 如果我們想將元素/元件作為 props 傳遞給其它元件,可以用 children props ``` // Can we accept React elements (or components) as props? // Yes, through a special property on the props object called 'children' function Layout(props) { return <div className="container">{props.children}</div>; } // The children prop is very useful for when you want the same // component (such as a Layout component) to wrap all other components: function IndexPage() { return ( <Layout> <Header /> <Hero /> <Footer /> </Layout> ); } // different page, but uses same Layout component (thanks to children prop) function AboutPage() { return ( <Layout> <About /> <Footer /> </Layout> ); } ``` - 可以用三元運算子來條件顯示元件 ``` // if-statements are fine to conditionally show , however... // ...only ternaries (seen below) allow us to insert these conditionals // in JSX, however function Header() { const isAuthenticated = checkAuth(); return ( <nav> <Logo /> {/* if isAuth is true, show AuthLinks. If false, Login */} {isAuthenticated ? <AuthLinks /> : <Login />} {/* if isAuth is true, show Greeting. If false, nothing. */} {isAuthenticated && <Greeting />} </nav> ); } ``` - Fragments 是用來顯示多個元件的特殊元件,無需向 DOM 添加額外的元素 - Fragments 適合用在條件邏輯 ``` // we can improve the logic in the previous example // if isAuthenticated is true, how do we display both AuthLinks and Greeting? function Header() { const isAuthenticated = checkAuth(); return ( <nav> <Logo /> {/* we can render both components with a fragment */} {/* fragments are very concise: <> </> */} {isAuthenticated ? ( <> <AuthLinks /> <Greeting /> </> ) : ( <Login /> )} </nav> ); } ``` ### 列表和 keys - 使用 .map() 將資料列表(陣列)轉換為元素列表 ``` const people = ["John", "Bob", "Fred"]; const peopleList = people.map(person => <p>{person}</p>); ``` - .map() 也可用來轉換為元件列表 ``` function App() { const people = ['John', 'Bob', 'Fred']; // can interpolate returned list of elements in {} return ( <ul> {/* we're passing each array element as props */} {people.map(person => <Person name={person} />} </ul> ); } function Person({ name }) { // gets 'name' prop using object destructuring return <p>this person's name is: {name}</p>; } ``` - 迭代的每個 React 元素都需要一個特殊的 `key` prop - key 對於 React 來說是必須的,以便能夠追蹤每個正在用 map 迭代的元素 - 沒有 key,當資料改變時,React 較難弄清楚元素應該如何更新 - key 應該是唯一值,才能讓 React 知道如何分辨 ``` function App() { const people = ['John', 'Bob', 'Fred']; return ( <ul> {/* keys need to be primitive values, ideally a generated id */} {people.map(person => <Person key={person} name={person} />)} </ul> ); } // If you don't have ids with your set of data or unique primitive values, // you can use the second parameter of .map() to get each elements index function App() { const people = ['John', 'Bob', 'Fred']; return ( <ul> {/* use array element index for key */} {people.map((person, i) => <Person key={i} name={person} />)} </ul> ); } ``` ### 事件和事件處理器 - React 和 HTML 中的事件略有不同 ``` // Note: most event handler functions start with 'handle' function handleToggleTheme() { // code to toggle app theme } // in html, onclick is all lowercase <button onclick="handleToggleTheme()"> Submit </button> // in JSX, onClick is camelcase, like attributes / props // we also pass a reference to the function with curly braces <button onClick={handleToggleTheme}> Submit </button> ``` - 最該先學的 React 事件是 onClick 和 onChange - onClick 處理 JSX 元素上的點擊事件(也就是按鈕動作) - onChange 處理鍵盤事件(也就是打字動作) ``` function App() { function handleChange(event) { // when passing the function to an event handler, like onChange // we get access to data about the event (an object) const inputText = event.target.value; const inputName = event.target.name; // myInput // we get the text typed in and other data from event.target } function handleSubmit() { // on click doesn't usually need event data } return ( <div> <input type="text" name="myInput" onChange={handleChange} /> <button onClick={handleSubmit}>Submit</button> </div> ); } ``` ## React Hooks ### State and useState - useState 為我們提供 function component 中的本地狀態 ``` import React from 'react'; // create state variable // syntax: const [stateVariable] = React.useState(defaultValue); function App() { const [language] = React.useState('javascript'); // we use array destructuring to declare state variable return <div>I am learning {language}</div>; } ``` - 注意:此段文章中的任何 hook 都來自 React 套件,且可以單獨導入 ``` import React, { useState } from "react"; function App() { const [language] = useState("javascript"); return <div>I am learning {language}</div>; } ``` - useState 還為我們提供了一個 `setter` 函數來更新它的狀態 ``` function App() { // the setter function is always the second destructured value const [language, setLanguage] = React.useState("python"); // the convention for the setter name is 'setStateVariable' return ( <div> {/* why use an arrow function here instead onClick={setterFn()} ? */} <button onClick={() => setLanguage("javascript")}> Change language to JS </button> {/* if not, setLanguage would be called immediately and not on click */} <p>I am now learning {language}</p> </div> ); } // note that whenever the setter function is called, the state updates, // and the App component re-renders to display the new state ``` - useState 可以在單個元件中使用一次或多次 ``` function App() { const [language, setLanguage] = React.useState("python"); const [yearsExperience, setYearsExperience] = React.useState(0); return ( <div> <button onClick={() => setLanguage("javascript")}> Change language to JS </button> <input type="number" value={yearsExperience} onChange={event => setYearsExperience(event.target.value)} /> <p>I am now learning {language}</p> <p>I have {yearsExperience} years of experience</p> </div> ); } ``` - useState 可以接受 primitive value 或物件 ``` // we have the option to organize state using whatever is the // most appropriate data type, according to the data we're tracking function App() { const [developer, setDeveloper] = React.useState({ language: "", yearsExperience: 0 }); function handleChangeYearsExperience(event) { const years = event.target.value; // we must pass in the previous state object we had with the spread operator setDeveloper({ ...developer, yearsExperience: years }); } return ( <div> {/* no need to get prev state here; we are replacing the entire object */} <button onClick={() => setDeveloper({ language: "javascript", yearsExperience: 0 }) } > Change language to JS </button> {/* we can also pass a reference to the function */} <input type="number" value={developer.yearsExperience} onChange={handleChangeYearsExperience} /> <p>I am now learning {developer.language}</p> <p>I have {developer.yearsExperience} years of experience</p> </div> ); } ``` - 如果新狀態依賴於之前的狀態,我們可以在 setter 函數中使用一個函數來為我們提供之前狀態的值 ``` function App() { const [developer, setDeveloper] = React.useState({ language: "", yearsExperience: 0, isEmployed: false }); function handleToggleEmployment(event) { // we get the previous state variable's value in the parameters // we can name 'prevState' however we like setDeveloper(prevState => { return { ...prevState, isEmployed: !prevState.isEmployed }; // it is essential to return the new state from this function }); } return ( <button onClick={handleToggleEmployment}>Toggle Employment Status</button> ); } ``` ### side effects 和 useEffect - useEffect 讓我們在 function component 中執行副作用。什麼是副作用? - 副作用是我們需要接觸外部世界的地方。例如,從 API 獲取資料或操作 DOM。 - 副作用是可能以不可預測的方式,改變我們元件狀態的操作(導致「副作用」)。 - useEffect 接受 callback function(稱為 effect 函數),預設情況下,每次重新渲染時都會運行 - useEffect 在我們的元件載入後運行,可以準確在元件的各個生命週期觸發 ``` // what does our code do? Picks a color from the colors array // and makes it the background color function App() { const [colorIndex, setColorIndex] = React.useState(0); const colors = ["blue", "green", "red", "orange"]; // we are performing a 'side effect' since we are working with an API // we are working with the DOM, a browser API outside of React useEffect(() => { document.body.style.backgroundColor = colors[colorIndex]; }); // whenever state is updated, App re-renders and useEffect runs function handleChangeIndex() { const next = colorIndex + 1 === colors.length ? 0 : colorIndex + 1; setColorIndex(next); } return <button onClick={handleChangeIndex}>Change background color</button>; } ``` - 如果不想在每次渲染後都執行 callback function,可以在第二個參數傳一個空陣列 ``` function App() { ... // now our button doesn't work no matter how many times we click it... useEffect(() => { document.body.style.backgroundColor = colors[colorIndex]; }, []); // the background color is only set once, upon mount // how do we not have the effect function run for every state update... // but still have it work whenever the button is clicked? return ( <button onClick={handleChangeIndex}> Change background color </button> ); } ``` - useEffect 讓我們能夠在 dependencies 陣列的內容改變時,才執行 - dependencies 陣列是第二個參數,如果陣列中的任何一個值發生變化,effect function 將再次運行 ``` function App() { const [colorIndex, setColorIndex] = React.useState(0); const colors = ["blue", "green", "red", "orange"]; // we add colorIndex to our dependencies array // when colorIndex changes, useEffect will execute the effect fn again useEffect(() => { document.body.style.backgroundColor = colors[colorIndex]; // when we use useEffect, we must think about what state values // we want our side effect to sync with }, [colorIndex]); function handleChangeIndex() { const next = colorIndex + 1 === colors.length ? 0 : colorIndex + 1; setColorIndex(next); } return <button onClick={handleChangeIndex}>Change background color</button>; } ``` - 可以在 useEffect 最後回傳一個函數,來取消訂閱某些效果 ``` function MouseTracker() { const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 }); React.useEffect(() => { // .addEventListener() sets up an active listener... window.addEventListener("mousemove", handleMouseMove); // ...so when we navigate away from this page, it needs to be // removed to stop listening. Otherwise, it will try to set // state in a component that doesn't exist (causing an error) // We unsubscribe any subscriptions / listeners w/ this 'cleanup function' return () => { window.removeEventListener("mousemove", handleMouseMove); }; }, []); function handleMouseMove(event) { setMousePosition({ x: event.pageX, y: event.pageY }); } return ( <div> <h1>The current mouse position is:</h1> <p> X: {mousePosition.x}, Y: {mousePosition.y} </p> </div> ); } // Note: we could extract the reused logic in the callbacks to // their own function, but I believe this is more readable ``` - 使用 useEffect 撈取資料 - 請注意,如果要使用更簡潔的 async/awit 語法處理 promise,則需要建立一個單獨的函數(因為 effect callback function 不能是 async) ``` const endpoint = "https://api.github.com/users/codeartistryio"; // with promises: function App() { const [user, setUser] = React.useState(null); React.useEffect(() => { // promises work in callback fetch(endpoint) .then(response => response.json()) .then(data => setUser(data)); }, []); } // with async / await syntax for promise: function App() { const [user, setUser] = React.useState(null); // cannot make useEffect callback function async React.useEffect(() => { getUser(); }, []); // instead, use async / await in separate function, then call // function back in useEffect async function getUser() { const response = await fetch("https://api.github.com/codeartistryio"); const data = await response.json(); setUser(data); } } ``` ### 效能和 useCallback - useCallback 是一個用來提高元件性能的 hook - 如果你有一個經常重新渲染的元件,useCallback 可以防止元件內的 callback function 在每次元件重新渲染時都重新創建(導致元件重新運行) - useCallback 僅在其依賴項之一改變時重新運行 ``` // in Timer, we are calculating the date and putting it in state a lot // this results in a re-render for every state update // we had a function handleIncrementCount to increment the state 'count'... function Timer() { const [time, setTime] = React.useState(); const [count, setCount] = React.useState(0); // ... but unless we wrap it in useCallback, the function is // recreated for every single re-render (bad performance hit) // useCallback hook returns a callback that isn't recreated every time const inc = React.useCallback( function handleIncrementCount() { setCount(prevCount => prevCount + 1); }, // useCallback accepts a second arg of a dependencies array like useEffect // useCallback will only run if any dependency changes (here it's 'setCount') [setCount] ); React.useEffect(() => { const timeout = setTimeout(() => { const currentTime = JSON.stringify(new Date(Date.now())); setTime(currentTime); }, 300); return () => { clearTimeout(timeout); }; }, [time]); return ( <div> <p>The current time is: {time}</p> <p>Count: {count}</p> <button onClick={inc}>+</button> </div> ); } ``` ### Memoization 和 useMemo - useMemo 和 useCallback 非常相似,都是為了提高效能。但就不是為了暫存 callback function,而是為了暫存耗費效能的運算結果 - useMemo 允許我們「記憶」已經為某些輸入進行了昂貴計算的結果(之後就不用重新計算了) - useMemo 從計算中回傳一個值,而不是 callback 函數(但可以是一個函數) ``` // useMemo is useful when we need a lot of computing resources // to perform an operation, but don't want to repeat it on each re-render function App() { // state to select a word in 'words' array below const [wordIndex, setWordIndex] = useState(0); // state for counter const [count, setCount] = useState(0); // words we'll use to calculate letter count const words = ["i", "am", "learning", "react"]; const word = words[wordIndex]; function getLetterCount(word) { // we mimic expensive calculation with a very long (unnecessary) loop let i = 0; while (i < 1000000) i++; return word.length; } // Memoize expensive function to return previous value if input was the same // only perform calculation if new word without a cached value const letterCount = React.useMemo(() => getLetterCount(word), [word]); // if calculation was done without useMemo, like so: // const letterCount = getLetterCount(word); // there would be a delay in updating the counter // we would have to wait for the expensive function to finish function handleChangeIndex() { // flip from one word in the array to the next const next = wordIndex + 1 === words.length ? 0 : wordIndex + 1; setWordIndex(next); } return ( <div> <p> {word} has {letterCount} letters </p> <button onClick={handleChangeIndex}>Next word</button> <p>Counter: {count}</p> <button onClick={() => setCount(count + 1)}>+</button> </div> ); } ``` ### Refs 和 useRef - Refs 是所有 React 組件都可用的特殊屬性。允許我們在元件安裝時,創建針對特定元素/元件的引用 - useRef 允許我們輕鬆使用 React refs - 我們在元件開頭呼叫 useRef,並將回傳值附加到元素的 ref 屬性來引用它 - 一旦我們創建了一個引用,就可以用它來改變元素的屬性,或者可以呼叫該元素上的任何可用方法(比如用 .focus() 來聚焦) ``` function App() { const [query, setQuery] = React.useState("react hooks"); // we can pass useRef a default value // we don't need it here, so we pass in null to ref an empty object const searchInput = useRef(null); function handleClearSearch() { // current references the text input once App mounts searchInput.current.value = ""; // useRef can store basically any value in its .current property searchInput.current.focus(); } return ( <form> <input type="text" onChange={event => setQuery(event.target.value)} ref={searchInput} /> <button type="submit">Search</button> <button type="button" onClick={handleClearSearch}> Clear </button> </form> ); } ``` ## 進階 Hook ### Context 和 useContext - 在 React 中,盡量避免創建多個 props 來將資料從父元件向下傳遞兩個或多個層級 ``` // Context helps us avoid creating multiple duplicate props // This pattern is also called props drilling: function App() { // we want to pass user data down to Header const [user] = React.useState({ name: "Fred" }); return ( // first 'user' prop <Main user={user} /> ); } const Main = ({ user }) => ( <> {/* second 'user' prop */} <Header user={user} /> <div>Main app content...</div> </> ); const Header = ({ user }) => <header>Welcome, {user.name}!</header>; ``` - Context 有助於將 props 從父組件向下傳遞到多個層級的子元件 ``` // Here is the previous example rewritten with Context // First we create context, where we can pass in default values const UserContext = React.createContext(); // we call this 'UserContext' because that's what data we're passing down function App() { // we want to pass user data down to Header const [user] = React.useState({ name: "Fred" }); return ( {/* we wrap the parent component with the provider property */} {/* we pass data down the computer tree w/ value prop */} <UserContext.Provider value={user}> <Main /> </UserContext.Provider> ); } const Main = () => ( <> <Header /> <div>Main app content...</div> </> ); // we can remove the two 'user' props, we can just use consumer // to consume the data where we need it const Header = () => ( {/* we use this pattern called render props to get access to the data*/} <UserContext.Consumer> {user => <header>Welcome, {user.name}!</header>} </UserContext.Consumer> ); ``` - useContext hook 可以移除這種看起來很怪的 props 渲染模式,同時又能在各種 function component 中隨意使用 ``` const Header = () => { // we pass in the entire context object to consume it const user = React.useContext(UserContext); // and we can remove the Consumer tags return <header>Welcome, {user.name}!</header>; }; ``` ### Reducers 和 useReducer - Reducers 是簡單、可預測的(純)函數,它接受一個先前的狀態物件和一個動作物件,並回傳一個新的狀態物件。例如: ``` // let's say this reducer manages user state in our app: function reducer(state, action) { // reducers often use a switch statement to update state // in one way or another based on the action's type property switch (action.type) { // if action.type has the string 'LOGIN' on it case "LOGIN": // we get data from the payload object on action return { username: action.payload.username, isAuth: true }; case "SIGNOUT": return { username: "", isAuth: false }; default: // if no case matches, return previous state return state; } } ``` - Reducers 是一種強大的狀態管理模式,用於流行的 Redux 狀態管理套件(這套很常與 React 一起使用) - 與 useState(用於本地元件狀態)相比,Reducers 可以通過 useReducer hook 在 React 中使用,以便管理我們應用程序的狀態 - useReducer 可以與 useContext 配對來管理資料並輕鬆地將資料傳遞給元件 - useReducer + useContext 可以當成應用程式的整套狀態管理系統 ``` const initialState = { username: "", isAuth: false }; function reducer(state, action) { switch (action.type) { case "LOGIN": return { username: action.payload.username, isAuth: true }; case "SIGNOUT": // could also spread in initialState here return { username: "", isAuth: false }; default: return state; } } function App() { // useReducer requires a reducer function to use and an initialState const [state, dispatch] = useReducer(reducer, initialState); // we get the current result of the reducer on 'state' // we use dispatch to 'dispatch' actions, to run our reducer // with the data it needs (the action object) function handleLogin() { dispatch({ type: "LOGIN", payload: { username: "Ted" } }); } function handleSignout() { dispatch({ type: "SIGNOUT" }); } return ( <> Current user: {state.username}, isAuthenticated: {state.isAuth} <button onClick={handleLogin}>Login</button> <button onClick={handleSignout}>Signout</button> </> ); } ``` ### 編寫 custom hooks - 創建 hook 就能輕鬆在元件之間重用某些行為 - hook 是一種比以前的 class component 更容易理解的模式,例如 higher-order components 或者 render props - 根據需要,隨時可以自創一些 hook ``` // here's a custom hook that is used to fetch data from an API function useAPI(endpoint) { const [value, setValue] = React.useState([]); React.useEffect(() => { getData(); }, []); async function getData() { const response = await fetch(endpoint); const data = await response.json(); setValue(data); }; return value; }; // this is a working example! try it yourself (i.e. in codesandbox.io) function App() { const todos = useAPI("https://todos-dsequjaojf.now.sh/todos"); return ( <ul> {todos.map(todo => <li key={todo.id}>{todo.text}</li>)} </ul> ); } ``` ### Hooks 規則 - 使用 React hooks 有兩個核心規則,要遵守才能正常運作: - 1. Hooks 只能在元件開頭呼叫 - Hooks 不能放在條件、迴圈或嵌套函數中 - 2. Hooks只能在 function component 內部使用 - Hooks 不能放在普通的 JavaScript 函數或 class component 中 ``` function checkAuth() { // Rule 2 Violated! Hooks cannot be used in normal functions, only components React.useEffect(() => { getUser(); }, []); } function App() { // this is the only validly executed hook in this component const [user, setUser] = React.useState(null); // Rule 1 violated! Hooks cannot be used within conditionals (or loops) if (!user) { React.useEffect(() => { setUser({ isAuth: false }); // if you want to conditionally execute an effect, use the // dependencies array for useEffect }, []); } checkAuth(); // Rule 1 violated! Hooks cannot be used in nested functions return <div onClick={() => React.useMemo(() => doStuff(), [])}>Our app</div>; } ``` --- 以上是快速整理,希望對您有幫助!

20 個一行 JavaScript 就能完成的小任務

一行程式碼可以做到很多事。這邊有20個小任務都用一行就可以完成,給您參考! - 原文出處:https://dev.to/saviomartin/20-killer-javascript-one-liners-94f # 獲取瀏覽器 Cookie 的值 讀取 `document.cookie` 來查 cookie 的值 ``` const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift(); cookie('_ga'); // Result: "GA1.2.1929736587.1601974046" ``` # 將 RGB 轉換為十六進制 ``` const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); rgbToHex(0, 51, 255); // Result: #0033ff ``` # 複製到剪貼板 使用 `navigator.clipboard.writeText` 輕鬆將任何文字複製到剪貼板。 ``` const copyToClipboard = (text) => navigator.clipboard.writeText(text); copyToClipboard("Hello World"); ``` # 檢查日期是否有效 使用以下程式碼檢查給定日期是否有效。 ``` const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf()); isDateValid("December 17, 1995 03:24:00"); // Result: true ``` # 查找一年中的第幾天 根據給定日期,找出是第幾天。 ``` const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24); dayOfYear(new Date()); // Result: 272 ``` # 將字串開頭大寫 Javascript 沒有內建的 capitalize 函數。我們可以使用以下程式碼來完成。 ``` const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1) capitalize("follow for more") // Result: Follow for more ``` # 求兩天之間的天數 使用以下程式碼查找 2 個給定日期之間的天數。 ``` const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000) dayDif(new Date("2020-10-21"), new Date("2021-10-22")) // Result: 366 ``` # 清除所有 Cookie 透過 document.cookie 存取 cookie 並清除它,就可輕鬆清除網頁中的所有 cookie。 ``` const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`)); ``` # 生成隨機十六進制顏色碼 使用“Math.random”和“padEnd”屬性,生成隨機的十六進制顏色碼。 ``` const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`; console.log(randomHex()); // Result: #92b008 ``` # 從陣列中刪除重複項 使用 JavaScript 中的 `Set` 輕鬆刪除重複項。 ``` const removeDuplicates = (arr) => [...new Set(arr)]; console.log(removeDuplicates([1, 2, 3, 3, 4, 4, 5, 5, 6])); // Result: [ 1, 2, 3, 4, 5, 6 ] ``` # 從 URL 獲取查詢參數 您可以從 `window.location` 或原始 URL `goole.com?search=easy&page=3` 中輕鬆找出查詢參數 ``` const getParameters = (URL) => { URL = JSON.parse('{"' + decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') +'"}'); return JSON.stringify(URL); }; getParameters(window.location) // Result: { search : "easy", page : 3 } ``` # 把日期物件轉成時間 把日期物件以“hour::minutes::seconds”格式轉成時間。 ``` const timeFromDate = date => date.toTimeString().slice(0, 8); console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); // Result: "17:30:00" ``` # 檢查數字是偶數還是奇數 ``` const isEven = num => num % 2 === 0; console.log(isEven(2)); // Result: True ``` # 求數的平均值 使用 `reduce` 方法計算多個數字之間的平均值。 ``` const average = (...args) => args.reduce((a, b) => a + b) / args.length; average(1, 2, 3, 4); // Result: 2.5 ``` # 滾動到頂部 您可以使用 `window.scrollTo(0, 0)` 方法自動滾動到頂部。將 `x` 和 `y` 都設為 0。 ``` const goToTop = () => window.scrollTo(0, 0); goToTop(); ``` # 反轉字串 您可以使用 `split`、`reverse` 和 `join` 方法輕鬆反轉字串。 ``` const reverse = str => str.split('').reverse().join(''); reverse('hello world'); // Result: 'dlrow olleh' ``` # 檢查陣列是否為空 ``` const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0; isNotEmpty([1, 2, 3]); // Result: true ``` # 取得選中的文字 使用內建的 getSelection 屬性取得用戶選取中的文字。 ``` const getSelectedText = () => window.getSelection().toString(); getSelectedText(); ``` # 打亂陣列 使用 `sort` 和 `random` 方法打亂陣列。 ``` const shuffleArray = (arr) => arr.sort(() => 0.5 - Math.random()); console.log(shuffleArray([1, 2, 3, 4])); // Result: [ 1, 4, 3, 2 ] ``` # 檢測深色模式 使用以下程式碼,檢查用戶的設備是否處於深色模式。 ``` const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches console.log(isDarkMode) // Result: True or False ``` --- 希望這些程式碼,有給您一些靈感!

在 JavaScript 新版 ES2020 之中,值得留意的 10 個新功能

ES2020 已經上線一段時間了,但是滿多新功能都大家不太知道。這篇文章跟大家介紹一下! - 原文出處:https://dev.to/worldindev/10-new-javascript-features-in-es2020-that-you-should-know-3ohf # 1. BigInt BigInt 是最受期待的新功能之一,允許工程師處理資料時,能存一個更大的整數。 目前在 JavaScript 中可以儲存的最大整數是 `pow(2, 53) - 1`。BigInt 讓你可以存更大的數字。 ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/588khrk3rpei76gho4e9.png) 如上所示,需要在後面加上一個 `n`。這個 `n` 表示這是一個 BigInt ,讓 JavaScript 引擎(v8 引擎)能夠特別處理。 這個功能不向後兼容,因為傳統的數字系統是 IEEE754(不能支援這種大小的數字)。 # 2.Dynamic import 動態導入讓你可在程式碼中,有條件地動態導入模組。跟你現在用 Webpack 和 Babel 做的事一樣。 此功能讓你可以按需求讀取程式碼,也就是所謂的 code splitting。讓你不再需要 webpack 或其他模組打包工具就能做到。您還可以在 if-else 中有條件地載入程式碼。這有個額外好處,就是不會污染全域命名空間。 ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/utai4m6xcc1nk3aooqxf.png) # 3. Nullish Coalescing Nullish Coalescing 可以確實檢查 nullish 而不是 falsy 值。什麼是 nullish 與 falsy 值? 在 JavaScript 中,許多值都是 `falsy`,例如空字串、數字 0、`undefined`、`null`、`false`、`NaN` 等等。 但有時候你想要檢查 undefined 跟 null。這種情況下,就可以用新的運算子 `??` ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uupnryjugtdtb6xvv7yk.png) 如圖, **OR** 運算子始終回傳 truthy 值,而 ?? 運算子回傳 non-nullish 值。 # 4. Optional Chaining Optional Chaining 語法讓你可以取得深度嵌套的物件屬性,而不用擔心屬性不存在。如果找不到屬性,會回傳 undefined,而不會報錯壞掉。物件屬性可用,呼叫函數跟陣列也可以用。超方便!請參考: ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r4w5zkv64r0cs46xpjie.png) # 5. Promise.allSettled `Promise.allSettled` 方法接受一個 Promise 陣列,並且只有在所有 Promise 都完成時才 resolve 或 reject。 以前只能用 `race` 和 `all` 做出類似效果。 ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6xi1hpkcazxgxsl81d90.png) # 6. String#matchAll `matchAll` 是添加到 `String` 原型的新方法,與正則表達式相關。這將回傳一個迭代器,該迭代器依次返回所有匹配的組。舉例: ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nmmk478r36d1bfjovi1v.png) # 7. globalThis 如果你是寫跨平台的 JS 程式碼,可以在 Node 上運行、在瀏覽器運行、也可以在 web-workers 中運行,你很難操作全域物件。 因為對於瀏覽器來說它是 window ,對於 Node 來說是 global ,對於 web-workers 來說是 self。如果有其它的運行環境,它們的全局物件也都不同。 變成你需要自己寫一段來檢測環境。所以 ES2020 實作了 globalThis,無論您在哪裡執行,它始終引用全域物件: ![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u5dczfi8moefwl4y1jo6.png) # 8. 模組命名空間匯出 在 JavaScript 模組中,可以使用以下語法: ``` import * as utils from './utils.mjs' ``` ES2020 新增了相對的匯出語法: ``` export * as utils from './utils.mjs' ``` 這等同於以下內容: ``` import * as utils from './utils.mjs' export { utils } ``` # 9. 定義好 for-in 順序 雖然大部份瀏覽器都實做了一樣的順序,但 ECMA 規範其實沒有指定 for (x in y) 的運行順序。在 ES2020 中正式標準化了。 # 10. import.meta `import.meta` 物件帶有一個 `null` 原型。 考慮以下模組,`module.js`: ``` <script type="module" src="module.js"></script> ``` 您可以使用 import.meta 物件取得有關模組的元信息: ``` console.log(import.meta); // { url: "file:///home/user/module.js" } ``` 對於 external scripts,它代表存取腳本的 URL,對於 inline scripts,它代表檔案的 URL。 --- 以上簡單分享,希望對你有幫助!

關於 JavaScript 開發的 8 個少見、但還不錯用小技巧

JavaScipt 是非常流行的程式語言,其中有些少見技巧,但還不錯用,這篇文章會分享八個,給您參考看看! - 原文出處:https://dev.to/worldindev/8-javascript-tips-tricks-that-no-one-teaches-24g1 # 函數繼承 函數繼承就是先寫一個基礎函數,再寫一個擴充函數,來擴充屬性與方法,會像這樣: ``` // Base function function Drinks(data) { var that = {}; // Create an empty object that.name = data.name; // Add it a "name" property return that; // Return the object }; // Fuction which inherits from the base function function Coffee(data) { // Create the Drinks object var that = Drinks(data); // Extend base object that.giveName = function() { return 'This is ' + that.name; }; return that; }; // Usage var firstCoffee = Coffee({ name: 'Cappuccino' }); console.log(firstCoffee.giveName()); // Output: "This is Cappuccino" ``` # .map() 的替代方案 `.map()` 有一個替代方案,就是 `.from()`: ``` let dogs = [ { name: ‘Rio’, age: 2 }, { name: ‘Mac’, age: 3 }, { name: ‘Bruno’, age: 5 }, { name: ‘Jucas’, age: 10 }, { name: ‘Furr’, age: 8 }, { name: ‘Blu’, age: 7 }, ] let dogsNames = Array.from(dogs, ({name}) => name); console.log(dogsNames); // returns [“Rio”, “Mac”, “Bruno”, “Jucas”, “Furr”, “Blu”] ``` # 數字轉字串/字串轉數字 通常,要讓數字轉為字串,會這樣寫 ``` let num = 4 let newNum = num.toString(); ``` 然後字串轉數字,會這樣寫 ``` let num = "4" let stringNumber = Number(num); ``` 但有個更快的寫法是: ``` let num = 15; let numString = num + ""; // number to string let stringNum = + numString; // string to number ``` # 使用長度來調整和清空陣列 在 javascript 中,我們可以改寫 length 內建方法,直接設定一個新值。 舉個例: ``` let array_values = [1, 2, 3, 4, 5, 6, 7, 8]; console.log(array_values.length); // 8 array_values.length = 5; console.log(array_values.length); // 5 console.log(array_values); // [1, 2, 3, 4, 5] ``` 還能用來清空陣列: ``` let array_values = [1, 2, 3, 4, 5, 6, 7,8]; console.log(array_values.length); // 8 array_values.length = 0; console.log(array_values.length); // 0 console.log(array_values); // [] ``` # 使用陣列解構來交換值 陣列解構讓陣列或物件的屬性,可以拆出來到變數中。還可以用它來交換兩個元素,舉例如下: ``` let a = 1, b = 2 [a, b] = [b, a] console.log(a) // result -> 2 console.log(b) // result -> 1 ``` # 刪除陣列中的重複元素 這個技巧很簡單。比方說,我創建了一個包含重複元素的陣列,然後我想刪除重複項: ``` const array = [1, 3, 2, 3, 2, 1, true, false, true, 'Kio', 2, 3]; const filteredArray = [...new Set(array)]; console.log(filteredArray) // [1, 3, 2, true, false, "Kio"] ``` # for 迴圈的簡寫版 可以這樣寫: ``` const names = ["Kio", "Rio", "Mac"]; // Long Version for (let i = 0; i < names.length; i++) { const name = names[i]; console.log(name); } // Short Version for (let name of names) console.log(name); ``` # 效能監測 下面這張圖是 google 用秒數提示效能: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i7ed89oyhcyyjhqirvc6.png 在 JavaScript 中也能做到,就像這樣: ``` const firstTime = performance.now(); something(); const secondTime = performance.now(); console.log(`The something function took ${secondTime - firstTime} milliseconds.`); ``` --- 以上八個技巧,希望對您有幫助!

10 個現代 JavaScript 中的好用語法:新手推薦

在 ES6 版本之後,Javascript 多了很多好用的語法,建議新手一定要學起來這幾招。 - 原文出處:https://dev.to/azure/modern-javascript-10-things-you-should-be-using-starting-today-1adm # -1- 展開運算子 Spred operator 在物件或陣列前面寫 ... 可以很輕鬆地把資料展開,舉例來說: ## Spread array ``` let firstHalf = [ 'one', 'two']; let secondHalf = ['three', 'four', ...firstHalf]; ``` 寫起來非常簡潔。不然原本要這樣寫: ## NO Array spread ``` let firstHalf = [ 'one', 'two']; let secondHalf = ['three', 'four']; for(var i=0, i <firstHalf.length; i++ ) { secondHalf.push(firstHalf[i]); } ``` 用在物件也可以,能夠合併屬性: ## Spread object ``` const hero = { name: 'Xena - Warrior Princess', realName: 'Lucy Lawless' } const heroWithSword = { ...hero, weapon: 'sword' } ``` 不然的話,就要用迴圈來跑全部屬性: ## NO Object spread ``` let keys = Object.keys(hero); let obj = {}; for(var i=0; i< keys.length; i++) { obj[keys[i]] = keys[props[i]]; } ``` 舊寫法其實有 Object.assign() 可以用,看起來會像: ``` const heroWithSword = Object.assign({}, hero, {weapon:"sword"}) ``` 但展開運算子還是簡潔多了: ``` const heroWithSword = { ...hero, weapon: 'sword' } ``` # -2- 其餘參數 Rest parameter 其餘參數能夠將剩下的參數蒐集到一個陣列中。JavaScript 有足夠彈性可以處理這些參數。通常會這樣寫: ``` function add(first, second, ...remaining) { return first + second; } ``` 以上只是加總前兩個參數,也就是 add(1,2) 或 add(1,2,3, 4) 結果一樣。接著這樣改寫: ``` function add(first, second, ...remaining) { return first + second + remaining.reduce((acc, curr) => acc + curr, 0); } ``` 這樣就會把全部參數都加總在一起了。 如您所見,前面加上 ... 就可以搜集其餘參數。這是一種命名變數的方式而已,比較少人知道這招,但可以知道一下。 # -3- 字串插值 String interpolation 看過這種寫法嗎? ``` class Product { constructor(name, description, price) { this.name = name; this.description = description; this.price = price; } getDescription() { return " Full description \n" + " name: " + this.name + " description: " + this.description } } ``` 看看那個 getDescription() 方法,又長、跨行、又難讀。在大多數程式語言都只能這樣寫。幸好,有些程式語言支援字串插值,包括 JavaScript,所以可以改寫如下: ``` getDescription() { return `Full description \n: name: ${this.name} description ${this.description} `; } ``` 反引號 ` 可以定義多行字串。再使用 ${} 進行插值。是不是好多了呢:) # -4- 屬性縮寫 Shorthand properties 雖然還沒搞懂,你可能早就在用了。在 ES5 需要這樣寫: ``` function createCoord(x, y) { return { x: x, y: y } } ``` 在 ES6 之後,如果 : 後面名稱一樣,可以直接省略,像這樣: ``` function createCoord(x, y) { return { x, y } } ``` 簡潔多了吧? # -5- 方法屬性 Method properties 在物件裡面指向方法的寫法。以下是 ES5 寫法: ``` const math = { add: function(a,b) { return a + b; }, sub: function(a,b) { return a - b; }, multiply: function(a,b) { return a * b; } } ``` 在 ES6 之後可以少寫一大堆,像這樣: ``` const math = { add(a,b) { return a + b; }, sub(a,b) { return a - b; }, multiply(a,b) { return a * b; } } ``` # -6- 解構 Destructuring 解構用得好,有益身心健康。 ## Object destructuring 這段: ``` function handle(req, res) { const name = req.body.name; const description = req.body.description; const url = req.url; log('url endpoint', url); // lots of logic happening dbService.createPerson( name, description ) } ``` 有點難讀吧,但要從多層深度挖資料,就會寫成這樣。還能怎麼辦?其實有以下妙招喔: ``` function handle(req, res) { const { body: { name, description }, url }, = req; log('url endpoint', url); // lots of logic happening dbService.createPerson( name, description ) ``` 變成俐落的一行了。 ## Array destructuring 不只物件能用,陣列也可以用,像這段: ``` const array = [1,2,3,4,5,6]; const a = array[0]; const c = array[2]; ``` 可以更優雅地改寫成這樣: ``` const array = [1,2,3,4,5,6]; const [a, ,c, ...remaining] = array; // remaining = [4,5,6] ``` 上面的模式配對,就可以拆出我們需要的變數。如果要跳過某值,就寫 , , 即可。我另外多寫了一個 rest parameter 來取得其餘資料。 ## Parameter matching 函數的參數也能這樣寫。當函數有超過 2-3 個參數時,業界慣例常常是這樣寫: ``` function doSomething(config) { if(config.a) { ... } if(config.b) { ... } if(config.c) { ... } } ``` 更漂亮的寫法其實是: ``` function doSomething({ a, b, c }) { if(a) { ... } if(b) { ... } if(c) { ... } } ``` # -7- 陣列方法 ES6 有大量好用的陣列方法,例如: - find(),回傳符合條件的項目,否則回傳 null - findIndex(),尋找項目的索引 - some(), 確認是否包含符合條件的項目 - includes(), 確認是否包含某個項目 舉例說明如下: ``` const array = [{ id: 1, checked: true }, { id: 2 }]; arr.find(item => item.id === 2) // { id: 2 } arr.findIndex(item => item.id === 2) // 1 arr.some(item => item.checked) // true const numberArray = [1,2,3,4]; numberArray.includes(2) // true ``` # -8- Promises + Async/Await 在只有 callback 能寫的年代,這種寫法很常見: ``` function doSomething(cb) { setTimeout(() => { cb('done') }, 3000) } doSomething((arg) => { console.log('done here', arg); }) ``` 用來寫非同步任務時,就會這樣寫。但現在我們有 promise 能寫了,所以可以這樣: ``` function doSomething() { return new Promise((resolve, reject) => { setTimeout(() => { resolve('done') }, 3000) }) } doSomething().then(arg => { console.log('done here', arg); }) ``` 多個流程還能整個串起來,就像這樣: ``` getUser() .then(getOrderByUser) .then(getOrderItemsByOrder) .then(orderItems => { // do something with order items }) ``` ## Async/await 接著還有 async/await 可以用。上方的範例,相關 promise 變成: ``` async function getItems() { try { const user = await getUser(); const order = await getOrderByUser(user); const items = await getOrderItemsByOrder(order); return items; } catch(err) { // handle error here, the suggestion to return something or rethrow } } getItems().then(items => { // do something with order items }) ``` 看起來像是同步,但其實非同步的一段程式碼:) # -9- 模塊 Modules 幾乎所有程式語言都支援模塊功能。將程式碼分為多個檔案,各自為獨立單元,就是模塊了。像這樣: ``` // math.js export function add(a,b) { return a + b; } export function sub(a,b) { return a - b; } export default (a,b) => a * b; // main.js import mult, { add, sub } from './math'; mult(2, 4) // 8 add(1,1) // 2 sub(1,2) // -1 ``` 使用 export 關鍵字來表示 add 跟 sub 是公開可用的。export default 代表不指定函數時直接導入的內容。在 main.js 中,將預設導入命名為 mult,然後指定導入函數 add 和 sub。 # -10- 箭頭函數 + this 整篇文章一直在用箭頭函數,其實只是另一種函數的寫法而已。以前要這樣寫: ``` function printArray(arr) { // do something } ``` 現在可以這樣寫: ``` const printArray = (arr) => { // do something } ``` ## 單行函數 函數還可以用一行寫完: ``` const add = (a,b) => a + b ``` 這種寫法可以省略 return 直接回傳結果。要回傳物件也可以,這樣即可: ``` const create = (a,b) = > ({ x: a, y: b }) ``` ## Lexical this 以前常常會搞混 this 代表什麼,舉例來說: ``` let array = [1,2,3]; function sum() { this.total = 0; arr.forEach(function(item) { this.total+= item; // `this` is the inner functions `this`, BAD }) return total; } ``` 這個例子中,this 在 forEach 指錯地方了。以前的解法是: ``` function sum() { this.total = 0; var self = this; arr.forEach(function(item) { self.total+= item; // now we are using `self`, it solves it but feels hacky }) return total; } ``` 雖然多寫個 self 變數可以解決,但實在很鳥。新的箭頭函數寫法則解決了這問題: ``` function sum() { this.total = 0; arr.forEach((item) => { this.total+= item; // all is well `this` points to outer function }) return total; } ``` # 結論 ES6 之後有很多好東西可以用,今天先介紹一些,希望對大家有幫助!

工程師大補丸:五個整理了大量學習資源的 github 專案

Github 是開發人員互相分享的寶庫。可以在上面找到任何與軟體工程有關的東西。就跟一般礦山一樣,要懂得採礦,才能得到有價值的礦物。 我一直在尋找 github 上面的寶庫,以下列出五個優質寶庫: - 原文出處:https://dev.to/wizdomtek/5-github-repositories-every-developer-should-know-1p93 # 1. Professional Programming 整理了大量經典書籍、優質網站的專案。 閱讀相關內容會有點花時間,但如果你想要持續提升自己,那這專案很適合你。 https://github.com/charlax/professional-programming # 2. Web Dev For Beginners 這是由 Microsoft 的 Azure Cloud Advocates 團隊,提供的 12週、24週線上課程。通通關於 JavaScript、CSS 和 HTML 基礎知識。每節課都包括課前和課後測驗、內容說明、解決方案、作業等。這種以寫專案為主的教學法,讓您一邊開發、一邊學習,是一種讓有效學習新技能的方法。 https://github.com/microsoft/Web-Dev-For-Beginners # 3. The art of command line 命令列是一門藝術,每個開發人員都有自己的使用習慣。最有用的指令是 man,可以用來查詢各種指令。 這個專案列出了各種常用指令與說明,值得一讀。 https://github.com/jlevy/the-art-of-command-line # 4. Project Based Learning 以專案開發為主的一系列學習資源。由一群熱心分享的工程師所整理。內含多種程式語言。 動手開發是學習程式設計的最好方法。不斷解決問題時,同時學習了知識。因為有了目標,大腦的記憶也更有效率。 https://github.com/practical-tutorials/project-based-learning # 5. Every Programmer Should Know 無論您有多熟練,您對技術的了解可能永遠都不夠。 聽起來很刺耳,但這句話是真的。技術世界太廣闊了,不可能了解一切。但這不是停止學習的理由。 瀏覽此專案,可以掌握很多新知識。 如果您想學習一些新鮮有趣的東西,可以將它當成學習工具。 https://github.com/mtdvio/every-programmer-should-know --- 以上,歡迎有空逛逛這些資源,祝您不斷變強。

7個超特別的工程師作品集網頁:讓您大開眼界

工程師要怎麼設計作品集網頁呢?來看看這些人的網頁,或許能給你一些靈感! - 原文出處:https://dev.to/ruppysuppy/7-developer-portfolio-for-inspiration-4no7 # 1. Bruno Simon 如果您有試過開發 3D 網站,那你一定聽過 Bruno Simon。他是 Three.js Journey 的作者。從他的作品集就可看出為什麼他是這個領域的高手。 他的作品集網站,本身就是一個電玩遊戲。你可以在裡面控制吉普車,在 3D 世界裡面開車,然後可在裡面探索他的作品集世界。這網站可說是作品集網站的巔峰之作。 https://bruno-simon.com/ ![](https://imgur.com/kqpLGNH.png) # 2. Robby Leonardi 另一個超厲害的作品集網站!Robby Leonardi 的作品集是一個互動式的履歷表,往下滑就可以瀏覽他的作品、看到更多個人資訊。 http://www.rleonardi.com/interactive-resume/ ![](https://imgur.com/tZ6QJcX.png) # 3. Nitin Ranganath 一個有創意、又很新潮的網站!整個作品集頁面,看起來就像是 VS Code 編輯器! https://vscode-portfolio.vercel.app/ ![](https://imgur.com/4ePEkBe.png) # 4. Dejan Markovic 與傳統網頁設計的風格大相徑庭,但實際操作起來,卻非常順暢、巧妙! https://www.dejan.works/ ![](https://imgur.com/w0jf0i6.png) # 5. Hype4 極簡主義風格的網站,具有超級簡潔、專業的設計感。 https://hype4.com/ ![](https://imgur.com/FhT8j3c.png) # 6. Jacek Jeznach 利用微互動來提高留存率的絕佳範例。雖然網站上的廣告很煩人,但對於互動細節的設計,值得您親自見識一下! https://jacekjeznach.com/ ![](https://imgur.com/NR7v2KV.png) # 7. Tapajyoti Bose 最後一個範例讓我老王賣瓜一下!😜 我做了一個帶有滾動特效的單頁式作品集網站! https://tapajyoti-bose.vercel.app/ ![](https://imgur.com/GpmgsPC.png) --- 以上,希望大家覺得有趣、有啓發性!

寫出優雅 JavaScript 程式碼的 8 個簡單技巧

Javascript 是一個很棒的程式語言,但是,要寫出乾淨的 javascript 程式碼可不簡單,即便是資深工程師也一樣。 乾淨的 JavaScript 程式碼該長怎樣?它應該要: - 易於閱讀 - 易於測試 - 高效和高性能 以下是您可以使用的優質工具和技巧,可將您的 Javascript 功力提升到全新水平: - 原文出處:https://dev.to/alexomeyer/8-must-know-tips-for-writing-clean-code-with-javascript-i4 # 1. 對所有 api 請求和 JSON 方法使用 try catch 發出 api 請求來撈資料時,許多事情都可能出錯,因此必須注意這些情況。在處理 JSON 時,不要自動信任拿到的資料格式,請試著處理可能出乎意料的格式,來讓您的程式碼更健壯。 ![](https://imgur.com/KVzrdd0.png) # 2. 使用 linter (ESLint) linter 是一種靜態程式碼分析工具,可根據一組預定義的規則和配置檢查程式和風格錯誤。簡而言之,它將改進您的 Javascript/Typescript 程式碼品質,並讓風格更加一致。 # 3. 在編輯器中​追蹤 Javascript issues 保持 Javascript 程式庫簡潔的一個重要方式,是能夠輕易追蹤和查看程式碼本身的問題。在編輯器中追蹤 issues 允許工程師: - 全面了解技術債等更大的問題 - 查看每問題的上下文 - 減少上下文前後查看的頻率 - 持續地處理技術債 您可以使用各種工具來追蹤您的技術債,但最快速、最簡單的入門方法是使用與 Jira、Linear、Asana 和其他專案管理工具整合的 VSCode 或 JetBrains 的免費 Stepsize 外掛。 # 4.使用模板字符串 模板字符串讓您在保留格式的同時將值注入字符串,並且程式碼比字串運算更容易閱讀。 ![](https://imgur.com/ccagbwx.png) # 5. 需要搜尋字串時,使用正規表示式 正規表示式雖然乍看之下很深奧,但它是非常強大的字串解析工具,允許您建立複雜的模式來解決各種困難的字串配對情境。 # 6. 使用可選串連運算子 停止使用冗長的邏輯運算子,使用可選串連運算子來簡化您的程式碼。 ![](https://imgur.com/4TtpBdm.png) # 7.避免巢狀結構 巢狀結構絕對會增加程式碼的複雜度,也讓它更難閱讀、更難理解。如果深度超過兩層,請考慮重構,改成在根層就有條件回傳、使用更短小的區塊、並將巢狀邏輯抽像化成獨立的函式。 # 8. 替所有特殊程式碼寫註解,但不要讓它取代程式碼可讀性 有時需要針對特殊情境寫專門處理。替這段程式碼寫註解,解釋它的功能與上下文的由來,這對其他工程師幫助會很大。也能幫助未來重讀這段的自己。但讓程式碼本身就很易讀還是最優先,不要習慣用寫註解來偷懶!

給工程師的12個超好用API、可串接大量有趣資料~!

不管是寫程式的新手、老手,在做專案的時候,常常需要資料,來讓專案內容更豐富吧! 這時候需要去找有趣、夠酷、免費的 API 來用! 這篇文章一次整理出 12 個有豐富資料的有趣 API!有空要用用看喔! - 原文出處:https://dev.to/monicafidalgo/12-apis-that-you-as-a-developer-will-love-it-4ec6 # ✨1. PokéAPI 來串寶可夢精靈 API 吧!可以撈到大量神奇寶貝資訊(動作、類型、能力)! - https://pokeapi.co/ - 需要 API 密鑰:否 # ✨2. GIPHY GIPHY 是世界上最大的 GIF 資料庫,可以撈到一大堆梗圖,方便你開發有趣的 side project! - https://developers.giphy.com/ - 需要 API 密鑰:是 # ✨3. Open Weather 串接這個API,馬上得知明天天氣!Open Weather API 收集和處理來自不同來源的天氣數據,例如全球和本地天氣模型、衛星、雷達、各種氣象站資訊! - https://openweathermap.org/api - 需要 API 密鑰:否 # ✨4. {JSON} Placeholder 快速撈一些 json 假資料,方便開發時有資料可以快速測試! - https://jsonplaceholder.typicode.com/ - 需要 API 密鑰:否 # ✨5. SWAPI 電影「星際大戰」API,擁有大量行星、宇宙飛船、車輛、電影和物種的數據~! - https://swapi.dev/ - 需要 API 密鑰:否 # ✨6. NASA NASA 就是美國國家航空暨太空總署,提供大量來自 NASA 的真實數據,包括 NASA 好奇號、機遇號和精神號探測器在火星上收集的圖像數據! - https://api.nasa.gov/ - 需要 API 密鑰:是 # ✨7. Unsplash 由大量攝影師上傳照片的優質圖片資料庫!開發網站首頁、串接漂亮照片的必備 API 網站! - https://unsplash.com/developers - 需要 API 密鑰:是 # ✨8. Dev.to dev.to 是國外一個開發者討論區,在上面寫文章的話,可以透過 API 把文章撈出來! - https://developers.forem.com/api - 需要 API 密鑰:否 # ✨9. Breaking Bad Netflix 神劇,《絕命毒師》的的 API。它可以讓你拿到劇中名言、人物、集數、各式死亡資訊! - https://breakingbadapi.com/documentation - 需要 API 密鑰:否 # ✨10. Random Data 想發揮創意並在專案中使用各種奇怪資料嗎?也許是一款隨機獲得啤酒或電腦的遊戲?試試看隨機資料 API 吧~! - https://random-data-api.com/documentation - 需要 API 密鑰:否 # ✨11. Rest Countries Rest Countries 讓您可以通過 RESTful API 拿到有關各個國家/地區的大量豐富資訊~! - https://restcountries.com/#rest-countries - 需要 API 密鑰:否 # ✨12. Rick and Morty Rick and Morty 系列很受工程師歡迎!這個 API 可以讓你按劇集、角色、地點進行查詢~! - https://rickandmortyapi.com/documentation - 需要 API 密鑰:否