🔍 搜尋結果:Hook

🔍 搜尋結果:Hook

改善重用性:Vue Composables 的推薦技巧&Design Patterns

本文將分為三個部分: 1. 通用設計模式 2. 我的建議 3. 進一步閱讀 享受並且讓我知道您在專案中使用的模式和實踐🚀 原文出處:https://dev.to/jacobandrewsky/good-practices-and-design-patterns-for-vue-composables-24lk ## 通用設計模式 我認為了解建置可組合項模式的最佳來源實際上是 Vue.js 文件,您可以在[此處](https://vuejs.org/guide/reusability/composables.html)查看 ### 基本可組合項 Vue 文件顯示了以下 useMouse 可組合項的示例: ``` // mouse.js import { ref, onMounted, onUnmounted } from 'vue' // by convention, composable function names start with "use" export function useMouse() { // state encapsulated and managed by the composable const x = ref(0) const y = ref(0) // a composable can update its managed state over time. function update(event) { x.value = event.pageX y.value = event.pageY } // a composable can also hook into its owner component's // lifecycle to setup and teardown side effects. onMounted(() => window.addEventListener('mousemove', update)) onUnmounted(() => window.removeEventListener('mousemove', update)) // expose managed state as return value return { x, y } } ``` 稍後可以在元件中使用它,如下所示: ``` <script setup> import { useMouse } from './mouse.js' const { x, y } = useMouse() </script> <template>Mouse position is at: {{ x }}, {{ y }}</template> ``` ### 異步可組合項 為了獲取資料,Vue 建議使用以下可組合結構: ``` import { ref, watchEffect, toValue } from 'vue' export function useFetch(url) { const data = ref(null) const error = ref(null) watchEffect(() => { // reset state before fetching.. data.value = null error.value = null // toValue() unwraps potential refs or getters fetch(toValue(url)) .then((res) => res.json()) .then((json) => (data.value = json)) .catch((err) => (error.value = err)) }) return { data, error } } ``` 然後可以在元件中使用它,如下所示: ``` <script setup> import { useFetch } from './fetch.js' const { data, error } = useFetch('...') </script> ``` ### 可組合合約 根據上面的示例,以下是所有可組合項都應遵循的約定: 1. 可組合文件名應以 use 開頭,例如 `useSomeAmazingFeature.ts` 2. 它可以接受輸入參數,這些參數可以是字串等基本類型,也可以接受 refs 和 getter,但需要使用 toValue 幫助器 3. Composable 應該返回一個 ref 值,該值可以在解構可組合項後存取,例如 `const { x, y } = useMouse()` 4. 可組合項可以保存可以在整個應用程式中存取和修改的全局狀態。 5. 可組合性可能會產生副作用,例如加入窗口事件偵聽器,但在卸載元件時應清除它們。 6. 可組合項只能在 `<script setup>` 或 `setup()` 掛鉤中呼叫。它們也應該在這些上下文中同步呼叫。在某些情況下,您還可以在生命週期掛鉤中呼叫它們,例如“onMounted()”。 7. 可組合項可以呼叫內部的其他可組合項。 8. 可組合項應在內部包裝某些邏輯,當過於復雜時,應將它們提取到單獨的可組合項中以便於測試。 ## 我的建議 我已經為我的工作專案和開源專案建置了多個可組合項 - NuxtAlgolia、NuxtCloudinary、NuxtMedusa,因此基於這些,我想根據我的經驗在上面的合同中加入一些要點。 ### 有狀態或/和純函數可組合項 在程式碼標準化的某個時刻,您可能會得出這樣的結論:您希望對可組合項中的狀態保留做出決定。 最容易測試的函數是那些不存儲任何狀態的函數(即它們是簡單的輸入/輸出函數),例如負責將字節轉換為人類可讀值的可組合函數。它接受一個值並返回一個不同的值 - 它不存儲任何狀態。 不要誤會我的意思,你不必做出“或”的決定。您可以完全保留有狀態和無狀態可組合項。但這應該是一個書面決定,以便以後更容易與他們合作 🙂 ### 可組合項的單元測試 我們希望使用 Vitest 為我們的前端應用程式實施單元測試。在後端工作時,進行單元測試程式碼覆蓋率非常有用,因為您主要關注邏輯。然而,在前端,您通常使用視覺效果。 因此,我們認為對整個元件進行單元測試可能不是最好的主意,因為我們基本上將對框架本身進行單元測試(如果按下按鈕,檢查狀態是否更改或模式是否打開)。 由於我們已將所有業務邏輯移至可組合項(基本上是 TypeScript 函數)內,因此它們很容易使用 Vitest 進行測試,並且允許我們擁有更穩定的系統。 ### 可組合項的範圍 不久前,在 VueStorefront 中,我們開發了自己的可組合方法(早在它們實際上像這樣被呼叫之前)。在我們的方法中,我們使用可組合項來映射電子商務的業務領域,如下所示: ``` const { cart, load, addItem, removeItem, remove, ... } = useCart() ``` 這種方法絕對有用,因為它允許將域包裝在一個函數中。在“useProduct”或“useCategory”等更簡單的示例中,實現和維護相對簡單。然而,正如您在此處的“useCart”示例中看到的那樣,當包裝一個包含更多邏輯而不僅僅是資料獲取的域時,這個可組合項正在發展成為一種非常難以開發和維護的形狀。 此時,我開始為 Nuxt 生態系統做出貢獻,其中引入了不同的方法。在這種新方法中,每個可組合項僅負責一件事。因此,我們的想法不是建置一個巨大的“useCart”可組合項,而是為每個功能建置可組合項,即“useAddToCart”、“useFetchCart”、“useRemovefromCart”等。 因此,維護和測試這些可組合項應該更容易 🙂 ## 進一步閱讀 這將是我的研究的全部內容。如果您想了解有關此主題的更多訊息,請務必查看以下文章: * https://vuejs.org/guide/reusability/composables.html * https://www.youtube.com/watch?v=bcZM3EogPJE * https://vueschool.io/articles/vuejs-tutorials/what-is-a-vue-js-composable/ * https://blog.logrocket.com/getting-started-vue-composables/ * https://macopedia.com/blog/news/how-can-vue-3-composables-make-your-life-easier

給新手參考:前端專案的檔案架構範例

在開發 Web 應用程式時建立可維護的檔案結構很重要,良好的架構有助於組織程式碼,並使其他開發人員了解您的 Web 應用程式結構。 原文出處:https://dev.to/noruwa/folder-structure-for-modern-web-applications-4d11 ### 設計檔案結構的一些技巧 - 了解您的 Web 專案的目的:為了弄清楚如何組織您的 Web 專案,您需要很好地了解專案需求 - 為您的文件夾和文件使用正確的命名慣例,它們應該描述您的 Web 應用程式的用途 ### 結構及說明 **Assets** assets 包含將在您的 Web 應用程式中使用的所有圖像、圖示、css 文件、字體文件等。自定義圖像、圖示、付費字體都放在這個文件夾中。 ![資產](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bosdpni04f4rhoscokrl.PNG) **Contexts** 當使用 React Js 作為您的前端 ui 庫時,context 文件夾存放所有跨元件和多個頁面使用的 react context 檔案。 ![上下文](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/34ah8q7qbthfe5pbkcbf.PNG) **Components** components 文件夾包含應用程式的 UI。包含我們所有的 UI 元件,如導航列、頁腳、按鈕、視窗、卡片等等。 ![元件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0fsm5cd609kxc1ydcv4b.PNG) ** Composables** 在 Vue 應用程式中,“Composables”是一種利用 Vue 的組合 API 來封裝和重用有狀態邏輯的功能。 **Data** 用來放會在不同部分和頁面中作為 JSON 文件使用的文本資料。這樣做將使資訊更新更容易。 ![資料 JSON](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/74ey2c253fveerw4ox3y.PNG) ![資料](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mybd8n92pxns26feb6qt.PNG) **Features** 包含每個頁面(身份驗證、主題、視窗)會用到的功能。例如,每個頁面可能都會用到視窗功能。 ![功能](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gljjlh0jgarivzabdamm.PNG) **Hooks** 讓 React 元件有狀態和生命週期特性的函數。我們還可以建立名稱以“use”開頭的自定義掛鉤,並可用於呼叫其他掛鉤。 ![掛鉤](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a84dq8pahtjgff63ru7e.PNG) **Layouts** 在定義網頁的總體外觀時,Layouts 文件夾會派上用場。它用於放置佈局的元件,例如側邊欄、導航欄和頁腳。如果您的 Web 應用程式有很多佈局,這個文件夾是保存它們的好地方。 ![佈局](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6h73gy0uruci8qlq5sjl.PNG) **Modules** Modules 文件夾處理應用程式中的特定任務。 ![模塊](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/boeni6zfudcg14201s87.PNG) **Pages** pages 目錄包含您的 Web 應用程式畫面。 Next Js 和 Nuxt Js 等前端框架中的頁面目錄,會讀取目錄中的所有文件並自動為您建立路由設定。 ** Public** 直接在伺服器根目錄提供服務,包含不會更改的公共文件,例如 favicon.ico。 **Routes** routes 文件夾只是你的 web 應用程式中的一個地方,用於存放到不同頁面的路由路徑。 ** Utility/Utils** 該文件夾用於存放所有實用函數,例如 auth、theme、handleApiError 等。 ** Views** Views 文件夾類似於 pages 文件夾,用來放頁面的重複部分。 ### 結論 良好的檔案結構可以讓您和其他開發人員更快地找到文件並更輕鬆地管理它們。希望這篇文章對您有幫助!

適用於各種軟體開發技能:2023 推薦練習的專案開發

作為一名開發人員,了解最新的技術和工具對於在就業市場上保持競爭力至關重要。 在這篇文章中,我們整理了一份 2023 年最熱門開發專案的完整列表,以及掌握每個專案的教程和資源。 無論您是希望提高技能的初學者,還是希望擴展您的技能組合的資深開發人員,此列表都適合每個人。 - 原文出處:https://dev.to/rahul3002/2023s-top-development-projects-for-programmers-a-complete-list-of-tutorials-and-tools-for-mastering-the-latest-technologies-37o3 --- ## 專案教程列表: ### Web開發: |專案 |技術 |連結 | | :--- |:---|:---| |使用 NextJS 建置 Reddit 2.0 克隆 | React、SQL、Supabase、Next.js、GraphQL | [連結](https://projectlearn.io/learn/web-development/project/build-reddit-2.0-clone-with-nextjs-205?from=github)| |使用 React 建置 YouTube 克隆 | Express、Node、JavaScript、HTML、CSS | [連結](https://projectlearn.io/learn/web-development/project/build-a-youtube-clone-with-react-200?from=github)| |使用 JavaScript 圖表庫建立發散條形圖 | JavaScript、HTML、CSS | [連結](https://projectlearn.io/learn/web-development/project/create-a-diverging-bar-chart-with-a-javascript-charting-library-197?from=github)| |通過建置卡片組件學習 CSS 基礎知識 | HTML, CSS | [連結](https://projectlearn.io/learn/web-development/project/learn-css-basics-by-building-a-card-component-196?from=github)| |建立無伺服器模因即服務 | JavaScript、Rust、CSS、HTML | [連結](https://projectlearn.io/learn/web-development/project/create-a-serverless-meme-as-a-service-194?from=github)| |天氣預報網站 | JavaScript、HTML、CSS、React | [連結](https://projectlearn.io/learn/web-development/project/weather-forecast-website-193?from=github)| |連結縮短網站 | JavaScript、Vue、HTML、CSS、React | [連結](https://projectlearn.io/learn/web-development/project/link-shortener-website-192?from=github)| |抄襲檢查器網站 | Python, 引導 | [連結](https://projectlearn.io/learn/web-development/project/plagiarism-checker-website-189?from=github)| |建置自定義 Google 地圖主題 | JavaScript、HTML、CSS | [連結](https://projectlearn.io/learn/web-development/project/build-a-custom-google-maps-theme-187?from=github)| |使用 JavaScript 建置超級馬里奧主題的 Google 地圖 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/web-development/project/build-a-super-mario-themed-google-map-with-javascript-180?from=github)| |建置社區驅動的交付應用程式 | Python、Django、PostgreSQL、JavaScript、Mapbox | [連結](https://projectlearn.io/learn/web-development/project/build-a-community-driven-delivery-application-176?from=github)| |建置本地商店搜尋和發現應用程式 | Python、Django、PostgreSQL、JavaScript、Mapbox | [連結](https://projectlearn.io/learn/web-development/project/build-a-local-store-search-and-discovery-application-175?from=github)| |使用 React.js 和 Node.js 的中型克隆 |React、Node、CSS3、JavaScript、HTML5 | [連結](https://projectlearn.io/learn/web-development/project/medium-clone-using-react.js-and-node.js-174?from=github)| |使用 React JS 克隆 Facebook |React、Firebase、CSS3、JavaScript、HTML5 | [連結](https://projectlearn.io/learn/web-development/project/facebook-clone-with-react-js-171?from=github)| | JavaScript30 - 30 天 Vanilla JS 編碼挑戰 | JavaScript | [連結](https://projectlearn.io/learn/web-development/project/javascript30---30-day-vanilla-js-coding-challenge-170?from=github)| |使用 Gatsby 和 GraphCMS 的旅行遺願清單地圖 |Gatsby、Leaflet、GraphCMS、HTML、CSS | [連結](https://projectlearn.io/learn/web-development/project/travel-bucket-list-map-with-gatsby-and-graphcms-168?from=github)| |使用 Vue.js 的記憶卡遊戲 | Vue、JavaScript、HTML、CSS | [連結](https://projectlearn.io/learn/web-development/project/memory-card-game-with-vue.js-167?from=github)| | Strapi 和 GatsbyJS 課程 - 投資組合專案 | Strapi、Gatsby、JavaScript、HTML、CSS | [連結](https://projectlearn.io/learn/web-development/project/strapi-and-gatsbyjs-course---portfolio-project-166?from=github)| | Storybook - Node、Express、MongoDB 和 Google OAuth | MongoDB、Node、JavaScript、HTML、CSS | [連結](https://projectlearn.io/learn/web-development/project/storybook---node,-express,-mongodb-and-google-oauth-165?from=github)| |呼吸和放鬆應用程式 - JavaScript 和 CSS 動畫 | JavaScript、HTML、CSS | [連結](https://projectlearn.io/learn/web-development/project/breathe-and-relax-app---javascript-and-css-animations-164?from=github)| |用於加密貨幣價格的 Node.js CLI |Node,JavaScript | [連結](https://projectlearn.io/learn/web-development/project/node.js-cli-for-cryptocurrency-prices-163?from=github)| | React 和 Tailwind CSS 圖片庫 |React,順風,JavaScript,HTML,CSS | [連結](https://projectlearn.io/learn/web-development/project/react-and-tailwind-css-image-gallery-162?from=github)| |使用 React 的番茄鐘 |React,JavaScript,HTML,CSS | [連結](https://projectlearn.io/learn/web-development/project/pomodoro-clock-using-react-161?from=github)| | Laravel 從零開始的關鍵字密度工具 | Laravel、PHP、JQuery、AJAX、SEO | [連結](https://projectlearn.io/learn/web-development/project/keyword-density-tool-with-laravel-from-scratch-160?from=github)| |使用 Yii2 PHP 框架克隆 YouTube | Yii2, PHP | [連結](https://projectlearn.io/learn/web-development/project/youtube-clone-using-yii2-php-framework-159?from=github)| |使用 React、GraphQL 和 Amplify 克隆 Reddit | React、Amplify、AWS、GraphQL、Node | [連結](https://projectlearn.io/learn/web-development/project/reddit-clone-with-react,-graphql-and-amplify-157?from=github)| |使用 React 和 GraphQL 的全棧 Yelp 克隆 |React、GraphQL、HTML、CSS、JavaScript | [連結](https://projectlearn.io/learn/web-development/project/full-stack-yelp-clone-with-react-and-graphql-155?from=github)| |帶有 React Hooks 和 Context API 的 Pokémon Web App |React、HTML、CSS、JavaScript | [連結](https://projectlearn.io/learn/web-development/project/pokémon-web-app-with-react-hooks-and-context-api-154?from=github)| |使用 JavaScript 和 Rails 進行分水嶺監控 | Ruby、Rails、JavaScript | [連結](https://projectlearn.io/learn/web-development/project/watershed-monitor-using-javascript-and-rails-153?from=github)| |使用 React 和 Redux 的氣候資料儀表板 | React、Redux、HTML、CSS、JavaScript | [連結](https://projectlearn.io/learn/web-development/project/climate-data-dashboard-using-react-and-redux-152?from=github)| |僅使用 CSS 翻轉 UNO 卡片 | HTML, CSS | [連結](https://projectlearn.io/learn/web-development/project/flipping-uno-cards-using-only-css-151?from=github)| |使用 Redis、WebSocket 和 Go 的聊天應用程式 | Redis、Web Socket、Go、Azure | [連結](https://projectlearn.io/learn/web-development/project/chat-app-with-redis,-websocket-and-go-146?from=github)| |使用 React 導航的 Spotify 登錄動畫 |React、HTML、CSS、JavaScript | [連結](https://projectlearn.io/learn/web-development/project/spotify-login-animation-with-react-navigation-145?from=github)| |僅使用 CSS 的動態天氣界面 | HTML, CSS | [連結](https://projectlearn.io/learn/web-development/project/dynamic-weather-interface-with-just-css-144?from=github)| |使用 Airtable 和 Vue 的簡單 CRUD 應用程式 | Airtable、Vue、Vuetify、API、HTML | [連結](https://projectlearn.io/learn/web-development/project/simple-crud-app-with-airtable-and-vue-143?from=github)| |帶有 MEVN 堆棧的全棧 RPG 角色生成器 | MongoDB、Express、Vue、Node、HTML | [連結](https://projectlearn.io/learn/web-development/project/full-stack-rpg-character-generator-with-mevn-stack-142?from=github)| |帶有 PERN 堆棧的 Todo 應用 | PostgreSQL、Express、React、Node、HTML | [連結](https://projectlearn.io/learn/web-development/project/todo-app-with-the-pern-stack-141?from=github)| |帶有 Gatsby 的夏季公路旅行地圖應用程式 |React,Gatsby,Leaflet | [連結](https://projectlearn.io/learn/web-development/project/summer-road-trip-mapping-app-with-gatsby-140?from=github)| |使用 Socket.io 的多人紙牌遊戲 | Phaser 3、Express、Socket.io、JavaScript | [連結](https://projectlearn.io/learn/web-development/project/multiplayer-card-game-with-socket.io-139?from=github)| |帶有 Gatsby 的 COVID-19 儀表板和地圖應用程式 |React,Gatsby,Leaflet | [連結](https://projectlearn.io/learn/web-development/project/covid-19-dashboard-and-map-app-with-gatsby-138?from=github)| | React 抽認卡測驗 |React、API、JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/web-development/project/flashcard-quiz-with-react-125?from=github)| |用純 JavaScript 打地鼠 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/web-development/project/whack-a-mole-with-pure-javascript-124?from=github)| |使用 JavaScript 的諾基亞 3310 貪吃蛇遊戲 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/web-development/project/nokia-3310-snake-game-using-javascript-123?from=github)| |原版 JavaScript 中的石頭剪刀布 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/web-development/project/rock-paper-scissors-in-vanilla-javascript-122?from=github)| |純 JavaScript 的俄羅斯方塊 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/web-development/project/tetris-with-pure-javascript-121?from=github)| |使用 React 製作 Meme Maker |React,JavaScript,HTML5,CSS3 | [連結](https://projectlearn.io/learn/web-development/project/meme-maker-with-react-119?from=github)| |使用 React 克隆 Evernote |React、Firebase、Node、JavaScript、HTML5 | [連結](https://projectlearn.io/learn/web-development/project/evernote-clone-with-react-118?from=github)| |開發者 Meetup App with Vue | Vue、Firebase、Vuetify、JavaScript、HTML5 | [連結](https://projectlearn.io/learn/web-development/project/developer-meetup-app-with-vue-117?from=github)| | Vue 實時聊天應用 | Vue、Firebase、Vuex、JavaScript、HTML5 | [連結](https://projectlearn.io/learn/web-development/project/real-time-chat-app-with-vue-116?from=github)| |使用 Vue 的加密貨幣追踪器 | Vue、Vuetify、API、JavaScript、HTML5 | [連結](https://projectlearn.io/learn/web-development/project/cryptocurrency-tracker-with-vue-115?from=github)| | Vue 多人問答遊戲 | Vue、Pusher、Node、Express、JavaScript | [連結](https://projectlearn.io/learn/web-development/project/multiplayer-quiz-game-with-vue-114?from=github)| | Vue 掃雷遊戲 | Vue、Vuex、Vuetify、JavaScript、HTML5 | [連結](https://projectlearn.io/learn/web-development/project/minesweeper-game-with-vue-113?from=github)| |使用 Vue 克隆 Instagram | Vue、CSSGram、JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/web-development/project/instagram-clone-with-vue-112?from=github)| |使用 Angular 克隆黑客新聞 |角度、燈塔、JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/web-development/project/hacker-news-clone-with-angular-111?from=github)| |聊天界面 | HTML5, CSS3 | [連結](https://projectlearn.io/learn/web-development/project/chat-interface-110?from=github)| |純 CSS3 工具提示 | HTML5, CSS3 | [連結](https://projectlearn.io/learn/web-development/project/pure-css3-tooltip-109?from=github)| |社交媒體按鈕 | HTML5, CSS3 | [連結](https://projectlearn.io/learn/web-development/project/social-media-buttons-108?from=github)| |推薦卡 | HTML5, CSS3 | [連結](https://projectlearn.io/learn/web-development/project/testimonial-card-107?from=github)| |帶有 CSS3 Flexbox 的導航欄 | HTML5, CSS3 | [連結](https://projectlearn.io/learn/web-development/project/navigation-bar-with-css3-flexbox-106?from=github)| |使用 CSS3 Flexbox 的移動應用程式佈局 | HTML5, CSS3 | [連結](https://projectlearn.io/learn/web-development/project/mobile-app-layout-with-css3-flexbox-105?from=github)| |受 Reddit 啟發的加載微調器 | HTML5, CSS3 | [連結](https://projectlearn.io/learn/web-development/project/reddit-inspired-loading-spinner-104?from=github)| |帶 CSS3 網格的日曆 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/web-development/project/calendar-with-css3-grid-103?from=github)| | React 中的俄羅斯方塊遊戲 |React,JavaScript,HTML5,CSS3 | [連結](https://projectlearn.io/learn/web-development/project/tetris-game-in-react-102?from=github)| | 2D 突圍遊戲 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/web-development/project/2d-breakout-game-101?from=github)| |精靈動畫 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/web-development/project/sprite-animation-100?from=github)| |蛇遊戲 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/web-development/project/snake-game-99?from=github)| |記憶遊戲 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/web-development/project/memory-game-98?from=github)| |簡單的身份驗證和授權 | GraphQL、Apollo、Node、JavaScript、HTML5 | [連結](https://projectlearn.io/learn/web-development/project/simple-authentication-and-authorization-97?from=github)| |加密貨幣追踪器 | NextJS、GraphQL、Apollo、Node、JavaScript | [連結](https://projectlearn.io/learn/web-development/project/cryptocurrency-tracker-96?from=github)| |使用 Vanilla Javascript 進行即時搜尋 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/web-development/project/instant-search-with-vanilla-javascript-95?from=github)| |計算器應用 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/web-development/project/calculator-app-94?from=github)| |待辦事項 | Vue、JavaScript、CSS3、HTML5 | [連結](https://projectlearn.io/learn/web-development/project/todo-app-45?from=github)| |博客應用 | Vue、GraphQL、阿波羅、JavaScript、CSS3 | [連結](https://projectlearn.io/learn/web-development/project/blog-app-44?from=github)| |簡單的預算應用程式 | Vue、布爾瑪、JavaScript、CSS3、HTML5 | [連結](https://projectlearn.io/learn/web-development/project/simple-budgeting-app-43?from=github)| |搜尋機器人 |Node、Twilio、Cheerio、API、自動化 | [連結](https://projectlearn.io/learn/web-development/project/search-bot-42?from=github)| |推特機器人 |Node、JavaScript、API、自動化 | [連結](https://projectlearn.io/learn/web-development/project/twitter-bot-41?from=github)| |實時 Markdown 編輯器 |Node、JavaScript、Express、Redis、HTML5 | [連結](https://projectlearn.io/learn/web-development/project/real-time-markdown-editor-40?from=github)| |待辦事項 | Angular、TypeScript、RxJS、HTML5、CSS3 | [連結](https://projectlearn.io/learn/web-development/project/todo-app-39?from=github)| |黑客新聞客戶端 |角度、RxJS、Webpack、HTML5、CSS3 | [連結](https://projectlearn.io/learn/web-development/project/hacker-news-client-38?from=github)| |隨機報價機 |React,JavaScript,HTML5,CSS3 | [連結](https://projectlearn.io/learn/web-development/project/random-quote-machine-37?from=github)| | Todoist克隆| React, Firebase, JavaScript, 測試, HTML5 | [連結](https://projectlearn.io/learn/web-development/project/todoist-clone-36?from=github)| |帶有情感分析的聊天應用 | NextJS、Pusher、Sentiment、Node、React | [連結](https://projectlearn.io/learn/web-development/project/chat-app-with-sentiment-analysis-35?from=github)| |預約安排 | React、Twilio、CosmicJS、Material-UI、JavaScript | [連結](https://projectlearn.io/learn/web-development/project/appointment-scheduler-34?from=github)| |生命遊戲 |React、2D、JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/web-development/project/game-of-life-33?from=github)| |新聞應用 | React Native、Node、API、React、JavaScript | [連結](https://projectlearn.io/learn/web-development/project/news-app-32?from=github)| |聊天應用 | React、Redux、Redux Saga、Web 套接字、Node | [連結](https://projectlearn.io/learn/web-development/project/chat-app-31?from=github)| |待辦事項 | React Native、GraphQL、Apollo、API、Hasura | [連結](https://projectlearn.io/learn/web-development/project/todo-app-30?from=github)| | Chrome 擴展 |React,包裹,JavaScript,HTML5,CSS3 | [連結](https://projectlearn.io/learn/web-development/project/chrome-extension-29?from=github)| |電影投票應用 | React、Redux、API、不可變、JavaScript | [連結](https://projectlearn.io/learn/web-development/project/movie-voting-app-27?from=github)| |特雷洛克隆 | React、Elixir、Phoenix、JWT、JavaScript | [連結](https://projectlearn.io/learn/web-development/project/trello-clone-25?from=github)| | Wiki 風格的 CMS | C#、.NET、Razor 頁面 | [連結](https://projectlearn.io/learn/web-development/project/wiki-style-cms-18?from=github)| |使用 ReactJS 克隆 Spotify |React,HTML5,CSS3 | [連結](https://projectlearn.io/learn/web-development/project/spotify-clone-with-reactjs-15?from=github)| |微軟主頁克隆 | HTML5、CSS3、JavaScript | [連結](https://projectlearn.io/learn/web-development/project/microsoft-homepage-clone-14?from=github)| |簡單甘特圖 | HTML5、CSS3、JavaScript | [連結](https://projectlearn.io/learn/web-development/project/simple-gantt-chart-13?from=github)| |工作抓取應用 |Node、JavaScript、REST、API、Express | [連結](https://projectlearn.io/learn/web-development/project/job-scraping-app-12?from=github)| |電子商務應用 |React,引導程序,JavaScript,HTML5,CSS3 | [連結](https://projectlearn.io/learn/web-development/project/e-commerce-app-11?from=github)| | Netflix 著陸頁 | HTML5、CSS3、JavaScript | [連結](https://projectlearn.io/learn/web-development/project/netflix-landing-page-10?from=github)| |人工智能聊天機器人 | Web 語音 API、Node、JavaScript、Express、Socket.io | [連結](https://projectlearn.io/learn/web-development/project/ai-chatbot-9?from=github)| |社交網絡應用 |React、Node、Redux、Firebase、REST | [連結](https://projectlearn.io/learn/web-development/project/social-networking-app-8?from=github)| |在 Node.js 中建置一個簡單的加密貨幣區塊鏈 |Node、JavaScript、密碼學、區塊鏈 | [連結](https://projectlearn.io/learn/web-development/project/build-a-simple-cryptocurrency-blockchain-in-node.js-7?from=github)| | BT 客戶端 |Node、JavaScript、TCP、計算機網絡 | [連結](https://projectlearn.io/learn/web-development/project/bittorrent-client-6?from=github)| |使用 JavaScript 的待辦事項列表應用 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/web-development/project/todo-list-app-with-javascript-4?from=github)| |使用 Anime.js 的 JavaScript 動畫 | JavaScript、CSS3、庫、HTML5、API | [連結](https://projectlearn.io/learn/web-development/project/javascript-animations-with-anime.js-3?from=github)| |帶有 React 的工作板應用程式 |React、Node、Cron、JavaScript、HTML5 | [連結](https://projectlearn.io/learn/web-development/project/job-board-app-with-react-1?from=github)| ### 移動開發: |專案 |技術 |連結 | | :--- |:---|:---| |使用 React Native 建置一個 Uber Eats 克隆 | React Native、Javascript、Android、iOS | [連結](https://projectlearn.io/learn/mobile-development/project/build-an-uber-eats-clone-with-react-native-204?from=github)| |使用 React Native 建置一個 Uber 克隆 | React Native、Javascript、Android、iOS | [連結](https://projectlearn.io/learn/mobile-development/project/build-an-uber-clone-with-react-native-203?from=github)| |使用 Flutter SDK 建置帶有故事的聊天應用程式 |顫振,飛鏢 | [連結](https://projectlearn.io/learn/mobile-development/project/build-a-chat-app-with-stories-using-the-flutter-sdk-199?from=github)| |建置 Robinhood 風格的應用程式來跟踪 COVID-19 病例 |科特林, 安卓 | [連結](https://projectlearn.io/learn/mobile-development/project/build-a-robinhood-style-app-to-track-covid-19-cases-198?from=github)| | Tinder 風格的 Swipe 移動應用程式 |科特林、Java、斯威夫特 | [連結](https://projectlearn.io/learn/mobile-development/project/tinder-style-swipe-mobile-app-186?from=github)| |加密貨幣價格列表移動應用程式 | React Native、Swift、Flutter、Dart | [連結](https://projectlearn.io/learn/mobile-development/project/cryptocurrency-price-listing-mobile-app-185?from=github)| |餐廳社交移動應用程式 | React Native、Swift、Flutter、Dart | [連結](https://projectlearn.io/learn/mobile-development/project/restaurants-social-mobile-app-184?from=github)| |休息時間提醒移動應用 | React Native、Kotlin、Java、Swift | [連結](https://projectlearn.io/learn/mobile-development/project/break-time-reminder-mobile-app-183?from=github)| |發票和付款提醒移動應用程式 | React、Node、Express、MongoDB | [連結](https://projectlearn.io/learn/mobile-development/project/invoicing-and-payment-reminder-mobile-app-182?from=github)| |倒計時移動應用 | Swift、Java、React Native | [連結](https://projectlearn.io/learn/mobile-development/project/countdown-mobile-app-181?from=github)| |使用 Swift 的 Flappy Bird iOS 遊戲 |斯威夫特、XCode、iOS | [連結](https://projectlearn.io/learn/mobile-development/project/flappy-bird-ios-game-using-swift-130?from=github)| |使用 Swift 的 Bull's Eye iOS 遊戲 |斯威夫特、XCode、iOS | [連結](https://projectlearn.io/learn/mobile-development/project/bull's-eye-ios-game-using-swift-129?from=github)| |使用 SwiftUI 的任務列表 iOS 應用 |斯威夫特、XCode、iOS | [連結](https://projectlearn.io/learn/mobile-development/project/task-list-ios-app-using-swiftui-128?from=github)| |使用 SwiftUI 的餐廳 iOS 應用 |斯威夫特、XCode、iOS | [連結](https://projectlearn.io/learn/mobile-development/project/restaurant-ios-app-using-swiftui-127?from=github)| |使用 Swift 的骰子 iOS 應用 |斯威夫特、XCode、iOS | [連結](https://projectlearn.io/learn/mobile-development/project/dice-ios-app-with-swift-126?from=github)| | TrueCaller 克隆 | Java、MySQL、XAMPP、Android | [連結](https://projectlearn.io/learn/mobile-development/project/truecaller-clone-83?from=github)| |天氣應用 | Java, API, Android | [連結](https://projectlearn.io/learn/mobile-development/project/weather-app-82?from=github)| |電子商務應用 | Java、Firebase、Android | [連結](https://projectlearn.io/learn/mobile-development/project/e-commerce-app-81?from=github)| |聊天應用 | Java、Firebase、Android | [連結](https://projectlearn.io/learn/mobile-development/project/chat-app-80?from=github)| |待辦事項 | Flutter、Dart、Android、iOS | [連結](https://projectlearn.io/learn/mobile-development/project/todo-app-79?from=github)| |旅遊應用程式用戶界面 | Flutter、Dart、Android、iOS | [連結](https://projectlearn.io/learn/mobile-development/project/travel-app-ui-78?from=github)| | Reddit 客戶端 |安卓,科特林 | [連結](https://projectlearn.io/learn/mobile-development/project/reddit-client-46?from=github)| |待辦事項 | React Native、Android、iOS、JavaScript | [連結](https://projectlearn.io/learn/mobile-development/project/todo-app-24?from=github) |照片庫查看器 | C#、iOS、Xamarin、Visual Studio、Android | [連結](https://projectlearn.io/learn/mobile-development/project/photo-library-viewer-19?from=github)| |使用 React Native 克隆 WhatsApp | React Native、Node、GraphQL、Apollo、JavaScript | [連結](https://projectlearn.io/learn/mobile-development/project/whatsapp-clone-with-react-native-2?from=github)| ### 遊戲開發: |專案 |技術 |連結 | | :--- |:---|:---| |使用 Kaboom.js 建置超級馬里奧兄弟、塞爾達傳說和太空侵略者 | JavaScript,Kaboom | [連結](https://projectlearn.io/learn/game-development/project/build-super-mario-bros,-zelda,-and-space-invaders-with-kaboom.js-201?from=github) | |使用 TypeScript 建立打磚塊遊戲 |打字稿、HTML、CSS、JavaScript | [連結](https://projectlearn.io/learn/game-development/project/create-an-arkanoid-game-with-typescript-195?from=github)| |簡單遊戲 | Lua、LÖVE、Python、Pygame 零 | [連結](https://projectlearn.io/learn/game-development/project/simple-games-179?from=github)| | Python在線多人遊戲|蟒蛇 | [連結](https://projectlearn.io/learn/game-development/project/python-online-multiplayer-game-173?from=github)| |打敗他們格鬥遊戲 |統一,C# | [連結](https://projectlearn.io/learn/game-development/project/beat-em-up-fight-game-172?from=github)| |使用 Godot 3.1 的簡單 3D 遊戲 |戈多,C#,3D | [連結](https://projectlearn.io/learn/game-development/project/simple-3d-game-using-godot-3.1-150?from=github)| | Godot 中的簡單益智遊戲- Box and Switch |戈多,C#,二維 | [連結](https://projectlearn.io/learn/game-development/project/simple-puzzle-game-in-godot---box-and-switch-149?from=github)| | Godot 3 中的遊戲界面從頭開始 |戈多,C#,二維 | [連結](https://projectlearn.io/learn/game-development/project/game-interface-from-scratch-in-godot-3-148?from=github)| | Godot 的 2D 遊戲:玩家與敵人 |戈多,C#,二維 | [連結](https://projectlearn.io/learn/game-development/project/2d-game-with-godot:-player-and-enemy-147?from=github)| |使用 Socket.io 的多人紙牌遊戲 | Phaser 3、Express、Socket.io、JavaScript | [連結](https://projectlearn.io/learn/game-development/project/multiplayer-card-game-with-socket.io-139?from=github)| |使用 Unity 2D 和 Mirror 的多人紙牌遊戲 | C#、Unity、二維、鏡像 | [連結](https://projectlearn.io/learn/game-development/project/multiplayer-card-game-with-unity-2d-and-mirror-137?from=github)| | Rust 中的 Roguelike 教程 |生鏽,二維 | [連結](https://projectlearn.io/learn/game-development/project/roguelike-tutorial-in-rust-136?from=github)| | Rust 歷險記 - 一款基本的 2D 遊戲 |生鏽,二維 | [連結](https://projectlearn.io/learn/game-development/project/adventures-in-rust---a-basic-2d-game-135?from=github)| |使用 Ruby 的終端貪吃蛇遊戲 |紅寶石,二維 | [連結](https://projectlearn.io/learn/game-development/project/terminal-snake-game-with-ruby-134?from=github)| |使用 OpenGL 的太空入侵者 | OpenGL、C/C++、2D | [連結](https://projectlearn.io/learn/game-development/project/space-invaders-using-opengl-133?from=github)| | C 中的數獨求解器 | C/C++, 二維 | [連結](https://projectlearn.io/learn/game-development/project/sudoku-solver-in-c-132?from=github)| | C 中的國際象棋引擎 | C/C++, 二維 | [連結](https://projectlearn.io/learn/game-development/project/chess-engine-in-c-131?from=github)| |使用 Swift 的 Flappy Bird iOS 遊戲 |斯威夫特、XCode、iOS | [連結](https://projectlearn.io/learn/game-development/project/flappy-bird-ios-game-using-swift-130?from=github)| |使用 Swift 的 Bull's Eye iOS 遊戲 |斯威夫特、XCode、iOS | [連結](https://projectlearn.io/learn/game-development/project/bull's-eye-ios-game-using-swift-129?from=github)| |用純 JavaScript 打地鼠 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/game-development/project/whack-a-mole-with-pure-javascript-124?from=github)| |使用 JavaScript 的諾基亞 3310 貪吃蛇遊戲 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/game-development/project/nokia-3310-snake-game-using-javascript-123?from=github)| |原版 JavaScript 中的石頭剪刀布 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/game-development/project/rock-paper-scissors-in-vanilla-javascript-122?from=github)| |純 JavaScript 的俄羅斯方塊 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/game-development/project/tetris-with-pure-javascript-121?from=github)| | Vue 多人問答遊戲 | Vue、Pusher、Node、Express、JavaScript | [連結](https://projectlearn.io/learn/game-development/project/multiplayer-quiz-game-with-vue-114?from=github)| | Vue 掃雷遊戲 | Vue、Vuex、Vuetify、JavaScript、HTML5 | [連結](https://projectlearn.io/learn/game-development/project/minesweeper-game-with-vue-113?from=github)| | React 中的俄羅斯方塊遊戲 |React,JavaScript,HTML5,CSS3 | [連結](https://projectlearn.io/learn/game-development/project/tetris-game-in-react-102?from=github)| | 2D 突圍遊戲 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/game-development/project/2d-breakout-game-101?from=github)| |精靈動畫 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/game-development/project/sprite-animation-100?from=github)| |蛇遊戲 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/game-development/project/snake-game-99?from=github)| |記憶遊戲 | JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/game-development/project/memory-game-98?from=github)| |坦克射手 | 3D、統一、C# | [連結](https://projectlearn.io/learn/game-development/project/tanks-shooter-93?from=github)| | 2D Roguelike |二維、Unity、C# | [連結](https://projectlearn.io/learn/game-development/project/2d-roguelike-92?from=github)| |約翰·萊蒙鬧鬼的短途旅行 3D | 3D、統一、C# | [連結](https://projectlearn.io/learn/game-development/project/john-lemon's-haunted-jaunt-3d-91?from=github)| | VR 初學者:密室逃脫 |虛擬現實、Unity、C# | [連結](https://projectlearn.io/learn/game-development/project/vr-beginner:-the-escape-room-90?from=github)| |露比的冒險 |二維、Unity、C# | [連結](https://projectlearn.io/learn/game-development/project/ruby's-adventure-89?from=github)| |角色扮演遊戲 |二維、Unity、C# | [連結](https://projectlearn.io/learn/game-development/project/rpg-game-88?from=github)| |滾球| 3D、統一、C# | [連結](https://projectlearn.io/learn/game-development/project/roll-a-ball-87?from=github)| | FPS 微型遊戲 |統一,C# | [連結](https://projectlearn.io/learn/game-development/project/fps-microgame-86?from=github)| |平台微遊戲 | Unity、C#、2D | [連結](https://projectlearn.io/learn/game-development/project/platformer-microgame-85?from=github)| |卡丁車小遊戲 |統一,C# | [連結](https://projectlearn.io/learn/game-development/project/karting-microgame-84?from=github)| |街機射擊 | Lua,愛 | [連結](https://projectlearn.io/learn/game-development/project/arcade-shooter-47?from=github)| |生命遊戲 |React、2D、JavaScript、HTML5、CSS3 | [連結](https://projectlearn.io/learn/game-development/project/game-of-life-33?from=github)| |手工英雄 | C/C++、OpenGL、2D | [連結](https://projectlearn.io/learn/game-development/project/handmade-hero-23?from=github)| |突圍 | C/C++、OpenGL、2D | [連結](https://projectlearn.io/learn/game-development/project/breakout-22?from=github)| |俄羅斯方塊 | C/C++, 二維 | [連結](https://projectlearn.io/learn/game-development/project/tetris-21?from=github)| |紅白機遊戲 | C/C++、Python、二維 | [連結](https://projectlearn.io/learn/game-development/project/nes-game-20?from=github)| | Roguelike 遊戲 | C#、.NET、RogueSharp、MonoGame、RLNet | [連結](https://projectlearn.io/learn/game-development/project/roguelike-game-17?from=github)| |簡單的角色扮演遊戲 | C#、SQL、二維 | [連結](https://projectlearn.io/learn/game-development/project/simple-rpg-game-16?from=github)| ### 機器學習與人工智能: |專案 |技術 |連結 | | :--- |:---|:---| |使用 BeautifulSoup 建置網絡爬蟲 | Python, BeautifulSoup | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/build-a-web-scraper-using-beautifulsoup-202?from=github)| |從胸部 X 光檢測肺炎的 CNN |美國有線電視新聞網,蟒蛇 | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/cnn-that-detects-pneumonia-from-chest-x-rays-169?from=github)| |使用 AWS 在 Python 中自動更新資料可視化 | Python、AWS、Matplotlib | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/auto-updating-data-visualizations-in-python-with-aws-158?from=github)| |使用 GCP 和 Node 的 Twitter 情感分析工具 | API、GCP、Node、JavaScript | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/twitter-sentiment-analysis-tool-using-gcp-and-node-156?from=github)| |使用 CNN 進行 Twitter 情緒分析 | Python、Matplotlib、Numpy、熊貓 | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/twitter-sentiment-analysis-using-cnn-120?from=github)| |泰勒斯威夫特歌詞生成器 | Python、Keras、Numpy、熊貓 | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/taylor-swift-lyrics-generator-77?from=github)| | MNIST 數字辨識器 | Python、Keras、TensorFlow、Numpy、SciKit | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/mnist-digit-recognizer-76?from=github)| |訓練模型生成顏色 | Python、Keras、TensorFlow、Numpy | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/train-a-model-to-generate-colors-75?from=github)| |圖片說明生成器 | Python、TensorFlow、Numpy | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/image-caption-generator-74?from=github)| |使用 CNN 破解驗證碼系統 | Python、Keras、TensorFlow、OpenCV、Numpy | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/break-a-captcha-system-using-cnn-73?from=github)| |生成一張平均臉 | Python、OpenCV、Numpy、C/C++ | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/generate-an-average-face-72?from=github)| |圖像拼接 | Python、OpenCV、Numpy | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/image-stitching-71?from=github)| |手部關鍵點檢測 | Python、OpenCV、Numpy、C/C++ | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/hand-keypoint-detection-70?from=github)| |特徵臉 | Python、OpenCV、Numpy、C/C++ | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/eigenface-69?from=github)| |無人機目標檢測 | Python、OpenCV、Numpy | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/drone-target-detection-68?from=github)| |使用 Mask R-CNN 進行目標檢測 | Python、OpenCV、Numpy | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/object-detection-using-mask-r-cnn-67?from=github)| |面部地標檢測 | Python、OpenCV、DLib、Numpy | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/facial-landmark-detection-66?from=github)| |文本傾斜校正 | Python、OpenCV、Numpy | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/text-skew-correction-65?from=github)| | OCR 和文本辨識 | Python、OpenCV、Tesseract、Numpy | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/ocr-and-text-recognition-64?from=github)| |人數統計 | Python、OpenCV、Numpy | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/people-counter-63?from=github)| |文本檢測 | Python、OpenCV、Numpy | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/text-detection-62?from=github)| |語義分割 | Python、OpenCV、Numpy | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/semantic-segmentation-61?from=github)| |物件跟踪 | Python、OpenCV、Numpy、CamShift | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/object-tracking-60?from=github)| |人臉聚類 | Python、OpenCV、Numpy | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/face-clustering-59?from=github)| |條碼掃描儀 | Python、OpenCV、ZBar、Numpy | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/barcode-scanner-58?from=github)| |顯著性檢測 | Python、OpenCV、Numpy | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/saliency-detection-57?from=github)| |人臉檢測 | Python、OpenCV、Numpy | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/face-detection-56?from=github)| |文件掃描儀 | Python、OpenCV、Numpy、SciKit | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/document-scanner-55?from=github)| |音樂推薦 | Python、SciKit、Numpy、熊貓 | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/music-recommender-54?from=github)| |預測葡萄酒質量 | Python、Matplotlib、Numpy、熊貓 | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/predict-quality-of-wine-53?from=github)| |遺傳算法 | Python、SciKit、Numpy、熊貓 | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/genetic-algorithms-52?from=github)| |深夢 | Python、TensorFlow、可視化 | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/deepdream-51?from=github)| |股價預測| Python、SciKit、Matplotlib | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/stock-price-prediction-50?from=github)| |電影推薦系統 | Python, LightFM | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/movie-recommendation-systems-49?from=github)| | Twitter 情緒分析 | Python, API | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/twitter-sentiment-analysis-48?from=github)| |帶有情感分析的聊天應用 | NextJS、Pusher、Sentiment、Node、React | [連結](https://projectlearn.io/learn/machine-learning-and-ai/project/chat-app-with-sentiment-analysis-35?from=github)| --- **結論** 2023 年將成為令人振奮的發展年,新技術和工具層出不窮。 希望這篇文章對您有幫助。

在 React 使用 useWorker 來跑多執行緒,大幅改善 UX 效能

使用 useWorker 在單獨的執行緒中,處理昂貴且阻塞 UI 的任務。 眾所周知,Javascript 是一種單線程語言。所以,做任何昂貴的任務,它都會阻塞 UI 互動。用戶需要等到它完成,才能執行剩餘的其他操作,這會帶來糟糕的用戶體驗。 為了克服和執行這些任務,Javascript 有一個名為 [Web Workers](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers) 的解決方案,它允許在 web 中執行消耗效能的任務時,瀏覽器不會阻塞用戶界面,使用戶體驗非常流暢。 本篇文章簡單介紹這個 hook。 原文出處:https://dev.to/nilanth/multi-threaded-react-app-using-useworker-gf8 --- ## Web Workers Web Worker 是一個在後台執行而不影響用戶界面的腳本,因為它在一個單獨的線程而不是主線程中執行。所以它不會對用戶交互造成任何阻塞。 Web Worker 主要用於在 Web 瀏覽器中執行昂貴的任務,例如對大量資料進行排序、CSV 導出、圖像處理等。 ![工作線程](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p2ikpn8va49460arsuum.png) 參考上圖,我們可以看到一個昂貴的任務是由一個工作線程並行執行的,而不會阻塞主線程。當我們在主線程中執行相同的操作時,會導致 UI 阻塞。 ## React 中的 Concurrent mode 呢? React [並發模式](https://beta.reactjs.org/reference/react/startTransition) 不會並行執行任務。它將非緊急任務轉移,接著立即執行緊急任務。它使用相同的主線程來處理。 正如我們在下圖中看到的,緊急任務是使用上下文切換來處理的。例如,如果一個表正在呈現一個大型資料集,並且用戶試圖搜尋某些內容,React 會將任務切換為用戶搜尋,並首先處理它,如下所示。 ![任務切換](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7nc8978zlpi8gmrcxlnd.png) 當為同一任務使用 worker 時,表格渲染在一個單獨的線程中並行執行。檢查下圖。 ![反應工作者](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4tnoy22tqchmq8cuavdp.png) ## useWorker [useWorker](https://github.com/alewin/useWorker) 是一個通過 React Hooks 在簡單配置中使用 Web Worker API 的函式庫。它支持在不阻塞 UI 的情況下執行昂貴任務,支援 promise 而不是事件監聽器,還有一些值得注意的功能: 1. 結束超時 worker 的選項 2. 遠程依賴 3. Transferable 4. Worker status > useWorker 是一個 3KB 的庫 ## 為什麼不用 JavaScript 內置 web worker? 在使用 javascript web worker 時,我們需要加入一些複雜的配置,來設置多行程式碼的 worker。使用 useWorker,我們可以簡化 worker 的設置。讓我們在下面的程式碼中,看看兩者之間的區別。 ## 在 React App 中使用 JS Web Worker 時 ``` // webworker.js self.addEventListener("message", function(event) { var numbers = [...event.data] postMessage(numbers.sort()) }); ``` ``` //index.js var webworker = new Worker("./webworker.js"); webworker.postMessage([3,2,1]); webworker.addEventListener("message", function(event) { console.log("Message from worker:", event.data); // [1,2,3] }); ``` ## 在 React App 中使用 useWorker 時 ``` // index.js const sortNumbers = numbers => ([...numbers].sort()) const [sortWorker] = useWorker(sortNumbers); const result = await sortWorker([1,2,3]) ``` 正如我之前所說,與普通的 javascript worker 相比,`useWorker()` 簡化了配置。 讓我們與 React App 整合並執行高 CPU 密集型任務,來看看 useWorker() 的實際執行情況。 ## Quick Start 要將 useWorker() 加入到 React 專案,請使用以下命令 `yarn add @koale/useworker` 安裝套件後,導入 useWorker()。 `import { useWorker, WORKER_STATUS } from "@koale/useworker";` 我們從函式庫中導入 useWorker 和 WORKER_STATUS。 **useWorker()** 鉤子返回 workerFn 和 controller。 1. `workerFn` 是允許使用 web worker 執行函數的函數。 2.controller 由 status 和 kill 參數組成。 status 參數返回 worker 的狀態和用於終止當前執行的 worker 的 kill 函數。 讓我們用一個例子來看看 **useWorker()**。 使用 **useWorker()** 和主線程對大型陣列進行排序 首先建立一個SortingArray元件,加入如下程式碼 ``` //Sorting.js import React from "react"; import { useWorker, WORKER_STATUS } from "@koale/useworker"; import { useToasts } from "react-toast-notifications"; import bubleSort from "./algorithms/bublesort"; const numbers = [...Array(50000)].map(() => Math.floor(Math.random() * 1000000) ); function SortingArray() { const { addToast } = useToasts(); const [sortStatus, setSortStatus] = React.useState(false); const [sortWorker, { status: sortWorkerStatus }] = useWorker(bubleSort); console.log("WORKER:", sortWorkerStatus); const onSortClick = () => { setSortStatus(true); const result = bubleSort(numbers); setSortStatus(false); addToast("Finished: Sort", { appearance: "success" }); console.log("Buble Sort", result); }; const onWorkerSortClick = () => { sortWorker(numbers).then((result) => { console.log("Buble Sort useWorker()", result); addToast("Finished: Sort using useWorker.", { appearance: "success" }); }); }; return ( <div> <section className="App-section"> <button type="button" disabled={sortStatus} className="App-button" onClick={() => onSortClick()} > {sortStatus ? `Loading...` : `Buble Sort`} </button> <button type="button" disabled={sortWorkerStatus === WORKER_STATUS.RUNNING} className="App-button" onClick={() => onWorkerSortClick()} > {sortWorkerStatus === WORKER_STATUS.RUNNING ? `Loading...` : `Buble Sort useWorker()`} </button> </section> <section className="App-section"> <span style={{ color: "white" }}> Open DevTools console to see the results. </span> </section> </div> ); } export default SortingArray; ``` 這裡我們配置了 useWorker 並傳遞了 bubleSort 函數來使用 worker 執行昂貴的排序。 接下來,將以下程式碼加入到 App.js 元件,並導入 SortingArray 元件。 ``` //App.js import React from "react"; import { ToastProvider } from "react-toast-notifications"; import SortingArray from "./pages/SortingArray"; import logo from "./react.png"; import "./style.css"; let turn = 0; function infiniteLoop() { const lgoo = document.querySelector(".App-logo"); turn += 8; lgoo.style.transform = `rotate(${turn % 360}deg)`; } export default function App() { React.useEffect(() => { const loopInterval = setInterval(infiniteLoop, 100); return () => clearInterval(loopInterval); }, []); return ( <ToastProvider> <div className="App"> <h1 className="App-Title">useWorker</h1> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <ul> <li>Sorting Demo</li> </ul> </header> <hr /> </div> <div> <SortingArray /> </div> </ToastProvider> ); } ``` 我們已將 React 徽標加入到 **App.js** 元件,該組件每 **100ms** 旋轉一次,以直觀地表示執行昂貴任務時的阻塞和非阻塞 UI。 執行上面的程式碼時,我們可以看到兩個按鈕 Normal Sort 和 Sort using **useWorker()**。 接下來,單擊 Normal Sort 按鈕在主線程中對陣列進行排序。我們可以看到 React 徽標停止旋轉幾秒鐘。由於排序任務阻塞了UI渲染,所以排序完成後logo又開始旋轉了。這是因為兩個任務都在主線程中處理。檢查以下gif ![正常排序](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k74iuo6qd36qbvpr9iaz.gif) 讓我們使用 [chrome 性能記錄](https://developer.chrome.com/docs/devtools/performance/) 檢查其性能分析。 ![性能正常](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8eclh8a6o7g9xzta03ic.png) 我們可以看到 Event: click 任務用了 **3.86 秒** 來完成這個過程,它阻塞了主線程 3.86 秒。 接下來,讓我們嘗試使用 **useWorker()** 選項進行排序。點擊它的時候我們可以看到 react logo 還在不間斷的旋轉。由於 useWorker 在不阻塞 UI 的情況下在後台執行排序。這使得用戶體驗非常流暢。檢查以下gif ![工人排序](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xe5ci0p3hy5nca4321cg.gif) 您還可以使用 `sortWorkerStatus` 在控制台中看到 worker 狀態為 **RUNNING**、**SUCCESS**。 讓我們看看這種方法的性能分析結果 ![主線程](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bxsl696fld6u79dqpwra.png) ![工作線程](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fcnwe2lczguyxgfqftrj.png) 正如我們所看到的,第一張圖片表示主線程中沒有長時間執行的進程。在第二張圖片中,我們可以看到排序任務由一個單獨的工作線程處理。所以主線程沒有阻塞任務。 您可以在以下沙箱中試用整個範例。 https://codesandbox.io/embed/useworker-sorting-example-041qhc?fontsize=14&hidenavigation=1&theme=dark ## 何時使用worker 1.圖像處理 2. 排序或處理大資料集。 3. 大資料CSV或Excel導出。 4. 畫布繪圖 5. 任何 CPU 密集型任務。 ## useWorker 的限制 1. web worker 無權存取 window 物件和 document。 2. 當 worker 正在執行時,我們不能再次呼叫它,直到它完成或被中止。為了解決這個問題,我們可以建立兩個或多個 useWorker() 鉤子實例。 3. Web Worker 無法返回函數,因為響應是序列化的。 4. Web Workers 受限於最終用戶機器的可用 CPU 內核和內存。 ## 結論 Web Worker 允許在 React 應用程式中使用多線程來執行昂貴的任務而不會阻塞 UI。而 useWorker 允許在 React 應用程式中以簡化的掛鉤方法使用 Web Worker API。 Worker 不應該被過度使用,我們應該只在必要時使用它,否則會增加管理 Worker 的複雜性。

JavaScript 系列七:第6課 ── 認識 Lifecycle Hooks 與 Watchers

## 課程目標 - 認識 Lifecycle Hooks 與 Watchers ## 課程內容 來認識一下 Lifecycle Hooks - https://vuejs.org/guide/essentials/lifecycle.html 簡單來說,在 vue 執行階段,又可分為 `mounted` `updated` `unmounted` 等等,將近十個時間點 根據應用程式的需要,可以在這十個時間點,進行必要的檢查&執行特定任務 但是,實務上,除了 `mounted` 經常用來跑一些初始化任務之外,其餘的時間點,幾乎不會用到 所謂 Lifecycle Hooks 是一個有點過時的觀念!稍微讀一下就好,相關功能大多被 Watchers 取代了 --- 接著就來認識一下 Watchers - https://vuejs.org/guide/essentials/watchers.html 簡單講,在 Vue 中,所謂的 Reactivity 已經很好用了: 「某些變數在更新之後,其他相關變數、以及畫面 UI,會跟著自動更新」 除此之外,還可以進一步使用更進階功能: 「隨時監控某些變數,如果發現它們更新,就執行一些相關的任務」 這些任務我們稱之為 `副作用(side effects)` 關於 side effects 怎麼解釋,是一個比較困難的主題 這邊先不詳談,目前有點困惑沒關係,作業中會讓你練習一下,先有點小感覺就好 ## 課後作業 承接上一課的作業 這一課要來做自動儲存功能 請使用 Watchers 去監聽 `notes` 狀態 每次 `notes` 有更新,就自動儲存到 Local Storage 裡面! 接著,在 `mounted` 裡面檢查 Local Storage 如果有資料,就把資料更新到 `notes` 裡面 如此一來,就完成了自動儲存功能,連儲存按鈕都不用做! --- 提示:普通的 watchers 不夠用,要使用 Deep Watchers 這部份有點難解釋,你先知道:普通的 data 變數型態,例如字串、數字、布林,可以用普通的 watcher 但如果是陣列或物件型態的 data,就要使用 Deep Watchers 先知道這樣就好 --- 做出以上功能,你就完成這次的課程目標了!

軟體開發者推薦使用:50 個好用的 CLI 指令工具

作為開發人員,我們在終端機上花費了大量時間。有很多有用的 CLI 工具,它們可以讓您在命令行中的生活更輕鬆、更快速,而且通常更有趣。 這篇文章概述了 50 個必備的好用 CLI 工具。 原文出處:https://dev.to/lissy93/cli-tools-you-cant-live-without-57f6 --- ## 工具 ### [`thefuck`](https://github.com/nvbn/thefuck) - 自動更正錯誤輸入的命令 > `thefuck` 是您一旦嘗試過就離不開的實用程式之一。每當您輸入錯誤的命令並出現錯誤時,只需執行 `fuck`,它就會自動更正它。使用向上/向下選擇一個更正,或者只執行 `fuck --yeah` 立即執行最有可能的。 ![他媽的示例用法](https://i.ibb.co/J55hWKX/thefuck.gif) --- ### [`zoxide`](https://github.com/ajeetdsouza/zoxide) - 輕鬆導航 _(更好的 cd)_ > `z` 讓您可以跳轉到任何目錄,而無需記住或指定其完整路徑。它會記住您存取過的目錄,因此您可以快速跳轉——您甚至不需要鍵入完整的文件夾名稱。它還具有互動式選項,使用“fzf”,因此您可以即時過濾目錄結果 ![zoxide-example-usage](https://i.ibb.co/6Z960jq/zoxide.gif) --- ### [`tldr`](https://github.com/tldr-pages/tldr) - 社區維護的文件 _(更好的 `man`)_ > `tldr` 是社區維護的手冊頁的巨大集合。與傳統的手冊頁不同,它們進行了總結,包含有用的用法範例,並且配色良好,便於閱讀 ![tldr-example-usage](https://i.ibb.co/jTW9knx/tlfr.gif) --- ### [`scc`](https://github.com/boyter/scc) - 計算程式碼行數_(更好的`cloc`)_ > `scc` 為您提供了針對特定目錄以每種語言編寫的程式碼行數的細分。它還顯示了一些有趣的統計資料,例如估計的開發成本和復雜性訊息。它的速度非常快,非常準確,並且支持多種語言 ![scc-example-usage](https://i.ibb.co/NygHWXt/scc.png) --- ### [`exa`](https://github.com/ogham/exa) - 列出文件 _(更好的 `ls`)_ > `exa` 是基於 Rust 的現代替代 `ls` 命令,用於列出文件。它可以顯示文件類型圖標、顏色、文件/文件夾訊息,並有多種輸出格式——樹、網格或列表 ![exa-example-usage](https://i.ibb.co/cTs0wQ5/exa.png) --- ### [`duf`](https://github.com/muesli/duf) - 硬碟使用量 _(更好的 `df`)_ > `duf` 非常適合顯示有關已安裝硬碟的訊息和檢查可用空間。它產生清晰多彩的輸出,並包括用於排序和自定義結果的選項。 ![duf-示例用法](https://i.ibb.co/sP59DKd/duf.png) --- ### [`aria2`](https://github.com/aria2/aria2) - 下載實用程式 _(更好的 `wget`)_ > `aria2` 是一種輕量級、多協議、用於 HTTP/HTTPS、FTP、SFTP、BitTorrent 和 Metalink 的恢復下載實用程序,支持通過 RPC 接口進行控制。它的[功能豐富](https://aria2.github.io/manual/en/html/README.html)令人難以置信,並且有大量的[選項](https://aria2.github.io/manual/en/ html/aria2c.html)。還有 [ziahamza/webui-aria2](https://github.com/ziahamza/webui-aria2) - 一個不錯的網路介面搭配。 ![aria2c-example-usage](https://i.ibb.co/pJkkX6x/aria2c.png) --- ### [`bat`](https://github.com/sharkdp/bat) - 讀取文件_(更好的`cat`)_ > `bat` 是 `cat` 的複製品,但具有語法高亮顯示和 git 集成。它是用 Rust 編寫的,性能非常好,並且有多個用於自定義輸出和主題的選項。支持自動管道和文件連接 ![bat-example-usage](https://i.ibb.co/VND3Y9s/bat.png) --- ### [`diff-so-fancy`](https://github.com/so-fancy/diff-so-fancy) - 文件比較_(更好的`diff`)_ > `diff-so-fancy` 為比較字串、文件、目錄和 git 更改提供了更好看的差異。更改突出顯示使發現更改變得更加容易,並且您可以自定義輸出佈局和顏色 ![diff-so-fancy-example-usage](https://i.ibb.co/RGKLhQk/diff-so-fancy.png) --- ### [`entr`](https://github.com/eradman/entr) - 觀察變化 > `entr` 允許您在文件更改時執行任意命令。您可以傳遞一個文件、目錄、符號連結或正則表達式來指定它應該監視哪些文件。它對於自動重建專案、響應日誌、自動化測試等非常有用。與類似專案不同,它使用 kqueue(2) 或 inotify(7) 來避免輪詢,並提高性能 ![entr-example-usage](https://i.ibb.co/HHKQx2H/entr.png) --- ### [`exiftool`](https://github.com/exiftool/exiftool) - 讀取+寫入元資料 > ExifTool 是一個方便的實用程序,用於讀取、寫入、剝離和建立各種文件類型的元訊息。再次分享照片時不要不小心洩露您的位置! ![exiftool-example-usage](https://i.ibb.co/Gv5PN6v/exiftool.png) --- ### [`fdupes`](https://github.com/jbruchon/jdupes) - 重複文件查找器 > `jdupes` 用於辨識和/或刪除指定目錄中的重複文件。當您有兩個或更多相同的文件時,它對於釋放硬碟空間很有用 ![fdupes-example-usage](https://i.ibb.co/jhSY2Nn/fdupes.png) --- ### [`fzf`](https://github.com/junegunn/fzf) - 模糊文件查找器_(更好的`find`)_ > `fzf` 是一個非常強大且易於使用的模糊文件查找器和過濾工具。它允許您跨文件搜尋字串或模式。 fzf 也有可用於大多數 shell 和 IDE 的[插件](https://github.com/junegunn/fzf/wiki/Related-projects),用於在搜尋時顯示即時結果。這篇由 Alexey Samoshkin 撰寫的 [文章](https://www.freecodecamp.org/news/fzf-a-command-line-fuzzy-finder-missing-demo-a7de312403ff/) 重點介紹了它的一些用例。 ![fzf-示例用法](https://i.ibb.co/LNcwjWm/fzf.gif) --- ### [`hyperfine`](https://github.com/sharkdp/hyperfine) - 命令基準測試 > `hyperfine` 可以輕鬆準確地對任意命令或腳本進行基準測試和比較。它負責預熱執行、清除緩存以獲得準確的結果並防止來自其他程序的干擾。它還可以將結果導出為原始資料並生成圖表。 ![hyperfine-example-usage](https://i.ibb.co/tKNR5gr/hyperfine.png) --- ### [`just`](https://github.com/casey/just) - 現代命令執行器_(更好的`make`)_ > `just` 與 `make` 類似,但增加了一些不錯的功能。它讓您可以將專案命令分組到副本中,這些副本可以輕鬆列出和執行。支持別名、位置參數、不同的 shell、dot env 集成、字串插入以及幾乎所有您可能需要的東西 --- ### [`jq`](https://github.com/stedolan/jq) - JSON 處理器 > `jq` 類似於 `sed`,但對於 JSON - 您可以使用它輕鬆地切片、過濾、映射和轉換結構化資料。它可用於編寫複雜的查詢以提取或操作 JSON 資料。還有一個 [jq playground](https://jqplay.org/),您可以用來試用,或通過即時回饋制定查詢 --- ### [`most`](https://www.jedsoft.org/most/) - 多窗口滾動尋呼機_(更好的 less)_ > `most` 是一個尋呼機,用於讀取長文件或命令輸出。 `most` 支持多窗口並且可以選擇不換行 --- ### [`procs`](https://github.com/dalance/procs) - 進程查看器_(更好的 ps)_ > `procs` 是一個易於導航的流程查看器,它具有彩色突出顯示,使流程的排序和搜尋變得容易,具有樹視圖和實時更新 ![procs-example-usage](https://i.ibb.co/y6qhgDX/procs-demo.gif) --- ### [`rip`](https://github.com/nivekuil/rip) - 刪除工具_(更好的 rm)_ > `rip` 是一種安全、符合人體工程學且高性能的刪除工具。它讓您直觀地刪除文件和目錄,並輕鬆恢復已刪除的文件 ![rip-example-usage](https://i.ibb.co/10DTvT2/rip.gif) --- ### [`ripgrep`](https://github.com/BurntSushi/ripgrep) - 在文件中搜尋 _(更好的 `grep`)_ > `ripgrep` 是一種面向行的搜尋工具,可遞歸地在當前目錄中搜尋正則表達式模式。它可以忽略 .gitignore 的內容並跳過二進製文件。它能夠在壓縮檔案中搜尋,或只搜尋特定的擴展名,並使用各種編碼方法理解文件 ![ripgrep-example-usage](https://i.ibb.co/qkMgQm9/ripgrep.png) --- ### [`rsync`](https://rsync.samba.org/) - 快速、增量文件傳輸 > `rsync` 讓您可以在本地複制大文件,或將大文件複製到遠程主機或外部驅動器或從遠程主機或外部驅動器複製。它可用於保持多個位置的文件同步,非常適合建立、更新和恢復備份 --- ### [`sd`](https://github.com/chmln/sd) - 查找並替換_(更好的`sed`)_ > `sd` 是一種簡單、快速且直觀的查找和替換工具,基於字串文字。它可以在文件、整個目錄或任何管道文本上執行 ![sd-示例用法](https://i.ibb.co/G9CfcGS/sd.png) --- ### [`tre`](https://github.com/dduan/tre) - 目錄層次結構_(更好的`tree`)_ > `tre` 輸出當前目錄或指定目錄的樹形文件列表,並帶有顏色。使用“-e”選項執行時,它會為每個專案編號,並建立一個臨時別名,您可以使用該別名快速跳轉到該位置 ![tre-example-usage](https://i.ibb.co/CmMrZLB/tre.png) --- ### [`xsel`](https://github.com/kfish/xsel) - 存取剪貼板 > `xsel` 讓您通過命令行讀取和寫入 X 選擇剪貼板。它對於將命令輸出通過管道傳輸到剪貼板或將復制的資料傳輸到命令中很有用 --- ## CLI 監控和性能應用程式 ### [`bandwhich`](https://github.com/imsnif/bandwhich) - 頻寬利用率監視器 > 即時顯示頻寬使用情況、連接訊息、傳出主機和 DNS 查詢 ![bandwhich-example-usage](https://i.ibb.co/8jHHBD3/Screenshot-from-2023-01-18-22-45-32.png) --- ### [`ctop`](https://github.com/bcicen/ctop) - 容器指標和監控 > 類似於 `top`,但用於監控正在執行的(Docker 和 runC)容器的資源使用情況。它顯示實時 CPU、內存和網絡帶寬以及每個容器的名稱、狀態和 ID。還有一個內置的日誌查看器和管理(停止、啟動、執行等)容器的選項 ![ctop-example-usage](https://i.ibb.co/xGjyzZ2/ctop.gif) --- ### [`bpytop`](https://github.com/aristocratos/bpytop) - 資源監控_(更好的`htop`)_ > `bpytop` 是一種快速、交互式、可視化的資源監視器。它顯示了最熱門的執行進程、最近的 CPU、內存、磁盤和網絡歷史記錄。您可以從界面中導航、排序和搜尋——還支持自定義顏色主題 ![bpytop-example-usage](https://i.ibb.co/nj9jrhr/bpytop.gif) --- ### [`glances`](https://github.com/nicolargo/glances) - 資源監視器 + 網絡和 API > `glances` 是另一個資源監視器,但具有不同的功能集。它包括一個完全響應的 Web 視圖、一個 REST API 和歷史監控。它易於擴展,並且可以與其他服務集成 ![掃視示例用法](https://i.ibb.co/6g65Qy4/glances.gif) --- ### [`gping`](https://github.com/orf/gping) - 交互式 ping 工具 _(更好的 `ping`)_ > `gping` 可以在多個主機上執行 ping 測試,同時以實時圖形顯示結果。當與 --cmd 標誌一起使用時,它還可以用於監視執行時間 ![gping 示例用法](https://i.ibb.co/CvG6xt0/gping.gif) --- ### [`dua-cli`](https://github.com/Byron/dua-cli) - 磁盤使用分析器和監視器 _(更好的 `du`)_ > `dua-cli` 讓您以交互方式查看每個已安裝驅動器的已用和可用磁盤空間,並輕鬆釋放存儲空間 ![dua-cli-usage-example](https://i.ibb.co/x3NbDLR/dua.gif) --- ### [`speedtest-cli`](https://github.com/sivel/speedtest-cli) - 命令行速度測試實用程序 > `speedtest-cli` 只是執行網路速度測試,通過 speedtest.net - 但直接從終端 :) ![speedtest-cli-example-usage](https://i.ibb.co/25QCbdF/speedtest-cli.gif) --- ### [`dog`](https://github.com/ogham/dog) - DNS 查找客戶端_(更好的`dig`)_ > `dog` 是一個易於使用的 DNS 查找客戶端,支持 DoT 和 DoH,漂亮的彩色輸出和發出 JSON 的選項 ![dog-example-usage](https://i.ibb.co/48n617Q/dog.png) --- ## CLI 生產力應用程式 > 上網衝浪、播放音樂、查看電子郵件、管理日曆、閱讀新聞等等,無需離開終端! ### [`browsh`](https://github.com/browsh-org/browsh) - CLI 網路瀏覽器 > `browsh` 是一個完全交互的、實時的、現代的基於文本的瀏覽器,呈現給 TTY 和瀏覽器。它同時支持鼠標和鍵盤導航,並且對於純基於終端的應用程式來說功能豐富得令人吃驚。它還緩解了困擾現代瀏覽器的電池耗盡問題,並且通過對 MoSH 的支持,由於帶寬減少,您可以體驗更快的加載時間 ![browsh-example-usage](https://i.ibb.co/S7nLFX5/browsh.gif) --- ### [`books`](https://github.com/jarun/books) - 書籤管理器 > `buku` 是一個基於終端的書籤管理器,具有大量的配置、存儲和使用選項。還有一個可選的 [web UI](https://github.com/jarun/buku/tree/master/bukuserver#screenshots) 和 [瀏覽器插件](https://github.com/samhh/bukubrow-webext#installation ), 用於在終端外存取您的書籤 ![buku-example-usage](https://i.ibb.co/CWQsf1x/buku.png) --- ### [`cmus`](https://github.com/cmus/cmus) - 音樂瀏覽器/播放器 > `cmus` 是終端音樂播放器,由鍵盤快捷鍵控制。它支持廣泛的音頻格式和編解碼器,並允許將曲目組織到播放列表中並應用播放設置 ![cmus-example-usage](https://i.ibb.co/dP6b3bd/cmus.png) --- ### [`cointop`](https://github.com/cointop-sh/cointop) - 跟踪加密價格 > `cointop` 顯示當前的加密貨幣價格,並跟踪您的投資組合的價格歷史。支持價格提醒、歷史圖表、貨幣換算、模糊搜尋等。您可以通過網絡 [cointop.sh](https://cointop.sh/) 或執行 `ssh cointop.sh` 來嘗試演示 ![cointop-example-usage](https://i.ibb.co/JBf9y4y/cointop.png) --- ### [`ddgr`](https://github.com/jarun/ddgr) - 從終端搜尋網頁 > `ddgr` 類似於 [googler](https://github.com/jarun/googler),但適用於 DuckDuckGo。它快速、乾淨、簡單,支持即時回答、搜尋完成、搜尋 bangs 和高級搜尋。它默認尊重您的隱私,也有 HTTPS 代理支持,並與 Tor 一起工作 ![dggr-example-usage](https://i.ibb.co/S0H21QH/dggr.png) --- ### [`micro`](https://github.com/zyedidia/micro) - 程式碼編輯器_(更好的`nano`)_ > `micro` 是一款易於使用、快速且可擴展的程式碼編輯器,支持鼠標。由於它被打包成一個二進製文件,安裝就像`curl https://getmic.ro | 安裝一樣簡單。慶典` --- ### [`khal`](https://github.com/pimutils/khal) - 日曆客戶端 > `khal` 是一個終端日曆應用程式,它顯示即將發生的事件、月份和議程視圖。您可以將它與任何 CalDAV 日曆同步,並直接加入、編輯和刪除事件 ![khal-example-usage](https://i.ibb.co/hLCdjZW/khal.png) --- ### [`mutt`](https://gitlab.com/muttmua/mutt) - 電子郵件客戶端 > `mut` 是一個經典的、基於終端的郵件客戶端,用於發送、閱讀和管理電子郵件。它支持所有主流電子郵件協議和郵箱格式,允許附件、密件抄送/抄送、線程、郵件列表和傳遞狀態通知 ![mutt-example-usage](https://i.ibb.co/zVVsG3s/mutt.webp) --- ### [`newsboat`](https://github.com/newsboat/newsboat) - RSS / ATOM 新聞閱讀器 > `newsboat` 是一個 RSS 提要閱讀器和聚合器,用於直接從終端閱讀新聞、博客和後續更新 ![newsboat-example-usage](https://i.ibb.co/fvT4YzD/newsboat.png) --- ### [`rclone`](https://github.com/rclone/rclone) - 管理雲存儲 > `rclone` 是一個方便的實用程序,用於將文件和文件夾同步到各種雲存儲提供商。它可以直接從命令行呼叫,也可以輕鬆集成到腳本中以替代繁重的桌面同步應用程式 --- ### [`taskwarrior`](https://github.com/GothenburgBitFactory/taskwarrior) - Todo + 任務管理 > `task` 是一個 CLI 任務管理/待辦事項應用程式。它既簡單又不引人注目,但也非常強大和可擴展,內置高級組織和查詢功能。還有很多(700+!)額外的[插件](https://taskwarrior.org/tools/) 用於擴展它的功能和與第三方服務的集成 ![任務戰士示例用法](https://i.ibb.co/7k6M37g/taskwarrior.jpg) --- ### [`tuir`](https://gitlab.com/ajak/tuir) - Reddit 的終端用戶界面 > `tuir` 是一個很好的選擇,如果你想看起來像在工作,同時實際瀏覽 Reddit!它具有直觀的鍵綁定、自定義主題,還可以呈現圖像和多媒體內容。還有 [haxor](https://github.com/donnemartin/haxor-news) 用於黑客新聞 ![tuir-example-usage](https://i.ibb.co/vzSw7s5/tuir.png) --- ## CLI 開發套件 ### [`httpie`](https://github.com/httpie/httpie) - HTTP/API測試測試客戶端 > `httpie` 是一個 HTTP 客戶端,用於測試、除錯和使用 API。它支持您所期望的一切——HTTPS、代理、身份驗證、自定義標頭、持久會話、JSON 解析。具有表達語法和彩色輸出的用法很簡單。與其他 HTTP 客戶端(Postman、Hopscotch、Insomnia 等)一樣,HTTPie 也包含一個 Web UI ![httpie-示例用法](https://i.ibb.co/Wk5S19g/httpie.png) --- ### [`lazydocker`](https://github.com/jesseduffield/lazydocker) - 完整的 Docker 管理應用程式 > `lazydocker` 是一個 Docker 管理應用程式,可讓您查看所有容器和圖像、管理它們的狀態、讀取日誌、檢查資源使用情況、重新啟動/重建、分析層、修剪未使用的容器、圖像和卷等等。它使您無需記住、鍵入和連結多個 Docker 命令。 ![lazy-docker-example-usage](https://i.ibb.co/MD8MWNH/lazydocker.png) --- ### [`lazygit`](https://github.com/jesseduffield/lazygit) - 完整的 Git 管理應用程式 > `lazygit` 是一個可視化的 git 客戶端,在命令行上。輕鬆加入、提交和推送文件、解決衝突、比較差異、管理日誌以及執行壓縮和倒帶等複雜操作。一切都有鍵綁定,顏色,而且很容易配置和擴展 ![lazy-git-example-usage](https://i.ibb.co/KLF3C6s/lazygit.png) --- ### [`kdash`](https://github.com/kdash-rs/kdash/) - Kubernetes 儀表板應用程式 > `kdash` 是一個一體化的 Kubernetes 管理工具。查看節點指標、觀察資源、流容器日誌、分析上下文和管理節點、pod 和命名空間 --- ### [`gdp-dashboard`](https://github.com/cyrus-and/gdb-dashboard) - 可視化 GDP 除錯器 > `gdp-dashboard` 向 GNU 除錯器加入了一個可視元素,用於除錯 C 和 C++ 程序。輕鬆分析內存、單步執行斷點和查看寄存器 ![gdp-dashboard-example-usage](https://i.ibb.co/2g2hVLh/gdp-dashboard.png) --- ## CLI 外部服務 ### [`ngrok`](https://ngrok.com/) - 共享本地主機的反向代理 > `ngrok` 安全* 將您的本地主機暴露在唯一 URL 後面的網路上。這使您可以與遠程同事實時共享您的工作。使用[非常簡單](https://notes.aliciasykes.com/p/RUi22QSyWe),但它也有很多高級功能,例如身份驗證、webhooks、防火牆、流量檢查、自定義/通配符域等等 ![ngrok-示例用法](https://i.ibb.co/4WPZNGx/ngrok.png) --- ### [`tmate`](https://tmate.io/) - 通過網路共享終端會話 > `tmate` 讓您立即與世界其他地方的人分享實時終端會話。跨系統工作,支持存取控制/授權,可自託管,具備Tmux的所有特性 --- ### [`asciinema`](https://asciinema.org/) - 錄製+分享終端會話 > `asciinema` 對於輕鬆記錄、共享和嵌入終端會話非常有用。非常適合展示您建置的內容,或展示教程的命令行步驟。與屏幕錄製視頻不同,用戶可以復制粘貼內容、動態更改主題和控製播放 --- ### [`navi`](https://github.com/denisidoro/navi) - 交互式備忘單 > `navi` 允許您瀏覽備忘單並執行命令。參數的建議值動態顯示在列表中。減少輸入,減少錯誤,讓自己不必記住數千條命令。它集成了 [tldr](https://github.com/tldr-pages/tldr) 和 [cheat.sh](https://github.com/chubin/cheat.sh) 以獲取內容,但您也可以導入其他備忘單,甚至編寫自己的備忘單 --- ### [`transfer.sh`](https://github.com/dutchcoders/transfer.sh/) - 快速文件共享 > `transfer` 使上傳和共享文件變得非常簡單,直接從命令行即可。它是免費的,支持加密,為您提供唯一的 URL,也可以自行託管。 > 我寫了一個 Bash 輔助函數來讓使用更容易一些,你可以[在這裡找到它](https://github.com/Lissy93/dotfiles/blob/master/utils/transfer.sh) 或嘗試一下通過執行`bash <(curl -L -s https://alicia.url.lol/transfer)` ![transfer-sh-example-usage](https://i.ibb.co/cCqDb1k/transfer-sh.png) --- ### [`surge`](https://surge.sh/) - 在幾秒鐘內部署一個站點 > `surge` 是一個免費的靜態託管服務提供商,您可以通過一個命令直接從終端部署到它,只需在您的 `dist` 目錄中執行 `surge`!它支持自定義域、自動 SSL 憑證、pushState 支持、跨域資源支持——而且是免費的! ![surge-sh-example-usage](https://i.ibb.co/NynprxZ/surge-sh.png) --- ### [`wttr.in`](https://github.com/chubin/wttr.in) - 查看天氣 > `wttr.in` 是一項以命令行中易於理解的格式顯示天氣的服務。只需執行“curl wttr.in”或“curl wttr.in/London”來嘗試一下。有 URL 參數來自定義返回的資料以及格式 ![wrrt-in-example-usage](https://i.ibb.co/J2JWnYT/Screenshot-from-2023-01-18-21-10-54.png) --- ## CLI 樂趣 ### [`cowsay`](https://en.wikipedia.org/wiki/Cowsay) - 讓 ASCII 牛說出你的訊息 > `cowsay` 是一個可配置的會說話的奶牛。它基於 Tony Monroe 的[原創](https://github.com/tnalpgge/rank-amateur-cowsay) ![cowsay-example-usage](https://i.ibb.co/TRqW3jD/cowsay.png) --- ### [`figlet`](http://www.figlet.org/) - 將文本輸出為大型 ASCII 藝術文本 > `figlet` 將文本輸出為 ASCII 藝術 ![figlet-example-usage](https://i.ibb.co/fk4T7D0/figlet.png) --- ### [`lolcat`](https://github.com/busyloop/lolcat) - 使控制台輸出彩虹色 > `lolcat` 使任何傳遞給它的文本變成彩虹色 ![lolcat-example-usage](https://i.ibb.co/nfp9Ycx/lolcat.png) --- ### [`neofetch`](https://github.com/dylanaraps/neofetch) - 顯示系統資料和 ditstro 訊息 > `neofetch` 打印發行版和系統訊息(這樣你就可以靈活地在 r/unixporn 上使用 Arch btw) ![neofetch-example-usage](https://i.ibb.co/x1PHpFC/Screenshot-from-2023-01-18-22-44-28.png) 例如,我使用 `cowsay`、`figlet`、`lolcat` 和 `neofetch` 來建立一個自定義的基於時間的 MOTD,在用戶首次登錄時顯示給他們。它以他們的名字問候他們,顯示伺服器訊息和時間、日期、天氣和 IP。 [這裡是源程式碼](https://github.com/Lissy93/dotfiles/blob/master/utils/welcome-banner.sh)。 ![歡迎](https://i.ibb.co/cTg0jyn/Screenshot-from-2023-01-18-22-59-28.png) --- ## 安裝和管理 我們大多數人都有一套核心的 CLI 應用程式和我們所依賴的實用程序。設置一台新機器並單獨安裝每個程序很快就會讓人厭煩。因此,安裝和更新終端應用程式的任務非常適合自動化。 [此處](https://github.com/Lissy93/dotfiles/tree/master/scripts/installs) 是我編寫的一些示例腳本,可以輕鬆將其放入您的點文件或獨立執行以確保您永遠不會錯過一個應用程式。 對於 MacOS 用戶,最簡單的方法是使用 [Homebrew](https://brew.sh/)。只需建立一個 Brewfile(使用 `touch ~/.Brewfile`),然後列出您的每個應用程式,然後執行 `brew bundle`。您可以通過將其放入 Git 存儲庫來備份您的包列表。這是一個示例,讓您入門:https://github.com/Lissy93/Brewfile 在 Linux 上,您通常希望使用本機包管理器(例如 `pacman`、`apt`)。例如,[這裡有一個腳本](https://github.com/Lissy93/dotfiles/blob/master/scripts/installs/arch-pacman.sh) 用於在 Arch Linux 系統上安裝上述應用程式 Linux 上的桌面應用程式可以通過 Flatpak 以類似的方式進行管理。同樣,[這是一個示例腳本](https://github.com/Lissy93/dotfiles/blob/master/scripts/installs/flatpak.sh) :) --- ## 結論 ...就是這樣 - 一個方便的 CLI 應用程式列表,以及一種在您的系統中安裝和保持它們最新的方法。 希望其中一些對你們中的一些人有用:)

7 個好用的 React Hooks:可以在很多專案直接使用

Hooks 是 React 最強大的功能之一。 它們使我們能夠輕鬆地在應用程式的元件中重用功能。掛鉤的最大優點在於它們的可重用性——您可以跨元件和專案重用掛鉤。 以下是我在每個 React 專案中重複使用的七個最重要的鉤子。今天就試一試,看看它們在建置您自己的 React 應用程式時是否有幫助吧。 原文出處:https://dev.to/webdevhero-com/7-react-hooks-for-every-project-1jdo --- 在我們開始之前,要先澄清一下:並非每個自定義 React 鉤子都需要由您編寫。事實上,我將提到的所有鉤子都來自一個庫“@mantine/hooks”。 Mantine 是一個很棒的第三方庫,其中包含這些鉤子等等。他們將為您的 React 應用程式加入您能想到的幾乎所有重要功能。 您可以在 [mantine.dev](https://mantine.dev) 查看“@mantine/hooks”的文件。 ## `useIntersection` 鉤子 當用戶在您的應用程式中向下滾動頁面時,您可能想知道某個元素何時對他們可見。 例如,您可能希望僅在用戶看到特定元素時才啟動動畫。或者,您可能希望在他們向下滾動頁面一定程度後,顯示或隱藏元素。 ![use intersection](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zilwvvdjppw9uz82iixo.gif) 要獲取有關元素是否可見的訊息,我們可以使用 **Intersection Observer API。**這是瀏覽器中內建的 JavaScript API。 我們可以使用純 JavaScript 單獨使用 API,但要知道有關特定元素是否在其滾動容器內,有個好方法是使用 useIntersection 掛鉤。 ``` import { useRef } from 'react'; import { useIntersection } from '@mantine/hooks'; function Demo() { const containerRef = useRef(); const { ref, entry } = useIntersection({ root: containerRef.current, threshold: 1, }); return ( <main ref={containerRef} style={{ overflowY: 'scroll', height: 300 }}> <div ref={ref}> <span> {entry?.isIntersecting ? 'Fully visible' : 'Obscured'} </span> </div> </main> ); } ``` 要使用它,我們需要做的就是在我們的元件中呼叫鉤子,並提供一個根元素。 Root 是滾動容器,可以使用 useRef 掛鉤將其作為 ref 提供。 `useIntersection` 回傳一個我們傳遞給目標元素的 ref,我們想要觀察其在滾動容器中的交集。 一旦我們有了對元素的引用,我們就可以追蹤元素是否相交。在上面的範例中,我們可以根據 entry.isIntersecting 的值查看元素何時被遮擋或何時完全可見。 您可以傳遞其他參數,這些參數允許您配置與目標可見百分比相關的**閾值**。 ## `useScrollLock` 鉤子 另一個與滾動相關的鉤子是 useScrollLock 鉤子。這個鉤子非常簡單:它使您能夠鎖定 body 元素上的任何滾動。 我發現當您想在當前頁面上顯示疊加層或跳出視窗,並且不想讓用戶在後台頁面上上下滾動時,它會很有幫助。這使您可以將注意力集中在視窗上,或允許在其自己的滾動容器內滾動。 ``` import { useScrollLock } from '@mantine/hooks'; import { Button, Group } from '@mantine/core'; import { IconLock, IconLockOpen } from '@tabler/icons'; function Demo() { const [scrollLocked, setScrollLocked] = useScrollLock(); return ( <Group position="center"> <Button onClick={() => setScrollLocked((c) => !c)} variant="outline" leftIcon={scrollLocked ? <IconLock size={16} /> : <IconLockOpen size={16} />} > {scrollLocked ? 'Unlock scroll' : 'Lock scroll'} </Button> </Group> ); } ``` `useScrollLock` 將用戶的滾動鎖定在頁面上的當前位置。該函數回傳一個陣列,它可以被解構,如上面的程式碼所示。 第二個值是一個允許我們鎖定滾動的函數。另一方面,第一個解構值是一個布林值,它告訴我們滾動條是否已被鎖定。 這個值很有用,例如,如果你想在滾動鎖定時顯示某些內容或告訴用戶它已被鎖定。您可以在下面的示例中看到,當滾動條被鎖定或解鎖時,我們會在我們的按鈕中進行指示。 ![use scroll lock](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wywccv7uexfrhfgayqj9.gif) ## `useClipboard` 鉤子 在許多情況下,您希望提供一個按鈕,允許用戶將內容複製到他們的剪貼板,這是存儲複製文本的地方。 一個很好的例子是,如果您的網站上有一個程式碼片段,並且您希望用戶輕鬆複製它。為此,我們可以使用另一個 Web API——**剪貼板 API**。 `@mantine/hooks` 為我們提供了一個方便的 `useClipboard` 鉤子,它回傳幾個屬性:`copied`,它是一個布林值,告訴我們是否已使用鉤子將值複製到剪貼板,以及` copy` 函數,我們可以將我們喜歡的任何字串值傳遞給它以進行複制。 在我們的範例中,我們想複製一個程式碼片段,供我們的用戶粘貼到他們喜歡的地方,如下面的影片所示: ![使用剪貼板](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6n0xd02vdg65bbfmb2xh.gif) ## useClipboard demo 當他們點擊我們指定的複制按鈕時,我們呼叫我們的 `copy` 函數,將程式碼片段傳遞給它,然後顯示一個小複選標記或向他們表明文本已被複製的東西。 巧妙的是 `useClipboard` 掛鉤帶有 **超時值**。在給定的超時時間(以毫秒為單位)之後,複製的狀態將被重置,向用戶顯示他們可以再次復製文本。 ## `useDebouncedValue` 鉤子 如果您的應用程式中有搜尋輸入,下一個鉤子“useDebouncedValue”是必不可少的。 每當用戶使用輸入執行搜尋時,搜尋操作通常涉及對 API 的 HTTP 請求。 您將遇到的一個典型問題是每次擊鍵都會執行查詢(請求),尤其是如果您希望用戶在鍵入時接收搜尋結果。即使對於一個簡單的搜尋查詢,也不需要在用戶完成輸入他們想要的內容之前執行這麼多請求。 這是 useDebounceValue 掛鉤的一個很好的用例,它對傳遞給它的文本應用「防抖」功能。 ``` import { useState } from 'react'; import { useDebouncedValue } from '@mantine/hooks'; import { getResults } from 'api'; function Demo() { const [value, setValue] = useState(''); const [results, setResults] = useState([]) const [debounced] = useDebouncedValue(value, 200); // wait time of 200 ms useEffect(() => { if (debounced) { handleGetResults() } async function handleGetResults() { const results = await getResults(debounced) setResults(results) } }, [debounced]) return ( <> <input label="Enter search query" value={value} style={{ flex: 1 }} onChange={(event) => setValue(event.currentTarget.value)} /> <ul>{results.map(result => <li>{result}</li>}</ul> </> ); } ``` 您使用 useState 將輸入的文本儲存在一個狀態中,並將狀態變數傳遞給 useDebouncedValue 。 作為該掛鉤的第二個參數,您可以提供一個等待時間,即值被「反抖」的時間段。反抖使我們能夠執行更少的查詢。 您可以在下面的影片中看到結果,用戶在其中鍵入內容,並且僅在 200 毫秒後,我們才能看到去抖值。 ![使用去抖值](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qfb5kqb6bxbkqfvog1hw.gif) ## `useMediaQuery` 鉤子 我一直使用的另一個非常有用的鉤子是 useMediaQuery 鉤子。 Media Queries 在純 CSS 中使用,`useMediaQuery` 鉤子允許我們訂閱我們傳遞給鉤子的任何媒體查詢。 例如,在我們的元件中,假設我們想要顯示一些文本或根據特定螢幕寬度(例如 900 像素)更改元件的樣式。我們像在 CSS 中一樣提供媒體查詢,並且 useMediaQuery 回傳給我們一個 true 或 false 的 matches 值。 ``` import { useMediaQuery } from '@mantine/hooks'; function Demo() { const matches = useMediaQuery('(min-width: 900px)'); return ( <div style={{ color: matches ? 'teal' : 'red' }}> {matches ? 'I am teal' : 'I am red'} </div> ); } ``` 它用 JavaScript 告訴我們媒體查詢的結果,這在我們想要使用 `style` 屬性在 JSX 中直接更改樣式時特別有用,例如。 ![使用媒體查詢](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7al1apywiq08ntgs4d8l.gif) 簡而言之,對於少數無法使用 CSS 處理媒體查詢的情況,這是一個必不可少的鉤子。 ## `useClickOutside` 鉤子 下一個掛鉤 - `useClickOutside` - 可能看起來很奇怪,但當您真正需要它時,您會發現它的重要性。 當你開發一個下拉菜單,或者在頁面內容前面彈出,並且之後需要關閉的東西時,這個鉤子是必不可少的。通過單擊按鈕打開這些類型的元件之一非常容易。關閉這些元件有點困難。 為了遵循良好的 UX 實踐,我們希望任何阻礙用戶視圖的東西都可以通過單擊元素外部輕鬆關閉。這正是 useClickOutside 掛鉤讓我們做的。 當我們呼叫 useClickOutside 時,它會返回一個 ref,我們必須將其傳遞給我們想要檢測點擊的外部元素。通常該元素將由一個布林狀態片段控制,例如我們在下面的示例中的狀態(即值“opened”)。 ``` import { useState } from 'react'; import { useClickOutside } from '@mantine/hooks'; function Demo() { const [opened, setOpened] = useState(false); const ref = useClickOutside(() => setOpened(false)); return ( <> <button onClick={() => setOpened(true)}>Open dropdown</button> {opened && ( <div ref={ref} shadow="sm"> <span>Click outside to close</span> </div> )} </> ); } ``` `useClickOutside` 接受一個回調函數,該函數控制當您實際單擊該元素外部時發生的情況。 在大多數情況下,我們想做一些非常簡單的事情,就是關閉它。為此,您可能需要一個狀態設置器(如 `setOpened`)並向其傳遞一個 false 值,然後隱藏您覆蓋的內容。 ![use click outside](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4jidp380brennyatol7w.gif) ## `useForm` 鉤子 在這個列表中,我最喜歡和最有用的鉤子是 `useForm` 鉤子。 這個鉤子專門來自 Mantine,涉及從庫中安裝一個特定的包:`@mantine/form`。它會為您提供在 React 中建立表單所需的一切,包括驗證輸入、顯示錯誤訊息以及在提交表單之前確保輸入值正確的能力。 `useForm` 接受一些初始值,這些初始值對應於您在表單中的任何輸入。 ``` import { TextInput, Button } from '@mantine/core'; import { useForm } from '@mantine/form'; function Demo() { const form = useForm({ initialValues: { email: '' }, validate: { email: (value) => (/^\S+@\S+$/.test(value) ? null : 'Invalid email'), }, }); return ( <div> <form onSubmit={form.onSubmit((values) => console.log(values))}> <TextInput withAsterisk label="Email" placeholder="[email protected]" {...form.getInputProps('email')} /> <Button type="submit">Submit</Button> </form> </div> ); } ``` `useForm` 的最大好處是它的助手,例如 `validate` 函數,它接收輸入到每個輸入的值,然後允許您建立驗證規則。 例如,如果您有一個電子郵件輸入,您可能有一個正則表達式來確定它實際上是否是一個有效的電子郵件(如您在上面的程式碼中所見)。如果沒有,那麼您可以顯示一條錯誤訊息並阻止提交表單。 ![使用表格](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n13l1gqejzx6y227p0j2.gif) 您如何獲取已輸入到表單中的值? Mantine 提供了一個非常方便的助手,叫做“getInputProps”,你只需提供你正在使用的輸入的名稱(比如電子郵件),它就會自動設置一個 onChange 來追蹤你在表單中輸入的值. 此外,為了處理表單提交,並在其值未通過驗證規則時阻止送出,它有一個特殊的 `onSubmit` 函數,您可以將其包裹在常規的 onSubmit 函數中。除了應用驗證規則之外,它還會負責在表單事件上呼叫 `preventDefault()`,這樣您就不必手動執行此操作。 我只用了這個鉤子的基本功能,但我強烈建議您在下一個專案中使用它。傳統上,表單很難正常工作,尤其是需要驗證和可見錯誤訊息的表單。 `useForm` 讓它變得異常簡單! --- 以上,簡單分享,希望對您有幫助。

利用新版 React 文件來學習並精通 functional components

**舊的 React 文件幾乎沒什麼用,這大家都知道,因為它沒反映該框架的現代用法。在本文中,我們將探索它的新文件並討論它為何很棒。** 原文出處:https://dev.to/diogorodrigues/reacts-new-killer-documentation-focused-only-on-functional-components-jnk --- React Hooks 與 [2019 年初版本 16.8](https://reactjs.org/blog/2019/02/06/react-v16.8.0.html) 一起發布,迅速流行起來並在前端社區中得到廣泛採用。通過這個版本,使用基於類別的元件編寫的複雜性,被有狀態的功能元件所取代。雖然我們可以在文件中找到對這些新功能的很好解釋,但大多數範例都繼續使用類別。 現在,在發生革命性變化 3 年多之後,**React 發布了其文件的 BETA 版本,從其解釋中刪除了類別,專注於使用帶有互動範例的鉤子的現代開發方式。** > “一旦我們與現有的 React 文檔達到內容一致,我們的目標是將此網站切換為主要網站。舊的 React 網站將存檔在一個子域中,因此您仍然可以存取它。舊內容鏈接將重定向到存檔的子域,該子域將有關於過時內容的通知。” - [BETA React 文檔](https://beta.reactjs.org/) _P.S.重要的是,當我寫這篇文章時,新內容幾乎 100% 完成了。_ ## 你可以在新的 React 文檔中找到什麼 雖然這個 React BETA 文檔不是很廣泛,但我不會逐個主題地介紹它,我將在下面重點介紹它的一些主要優點。 ### Quick Start 真的是非常快速的開始 **對我來說,這是改善超多的部分,因為與舊版本不同,現在我們可以通過其文檔中的互動式程式碼範例來使用 React 程式碼。** 這不是很神奇嗎? 一個完整的介紹,非常簡單,解釋清楚,並且不需要為現在開始學習的人設置任何專案。 ![React文檔交互示例演示](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cxsurynvrjpurbhla7pr.gif) ### 很好地解釋了使用 React Effects 的最佳方式 就個人而言,我認為**他們為解釋 Effects 所做的工作非常出色。**這確實是我研究了很多的東西,肯定會幫助我使用 React 開發更好的程式碼。 有一些詳盡的頁面展示了[如何停止將 Effects 視為生命週期掛鉤](https://beta.reactjs.org/learn/lifecycle-of-reactive-effects),而是 [Effects 作為與外部系統的同步器](https://beta.reactjs.org/learn/synchronizing-with-effects)。發生這種混淆是因為我們習慣於將使用 useEffect 鉤子的功能組件與基於類別的元件生命週期進行比較,但這不再有意義了。 https://twitter.com/dan_abramov/status/1157250198659354624 **另一個令人驚嘆的內容是 [“你可能不需要 effect”](https://beta.reactjs.org/learn/you-might-not-need-an-effect) 主題,我們可以在其中了解如何刪除不必要的效果**通過許多用例和互動式程式碼示例。您可以在下面的影片中找到關於該主題的精彩摘要。 https://www.youtube.com/watch?v=bGzanfKVFeU&t=742s&ab_channel=BeJS ### 精通狀態管理 我知道這個標題聽起來太冒險了,但是這個 React BETA 文檔有很多內容是關於[如何更好地建置狀態,避免冗餘狀態相關的錯誤](https://beta.reactjs.org/learn/managing-state),等等。 > “良好地建置狀態可以區分一個易於修改和除錯的元件,以及一個經常產生錯誤的組件。” - React 文檔 查看 [管理狀態部分](https://beta.reactjs.org/learn/managing-state) 以及 [Referencing Values with Refs](https://beta.reactjs.org/learn/referencing-values-with-refs) 主題以更好地理解 React 中狀態的使用。 ### 更多你可以在新的 React 文檔中找到的知識 我想強調的其他一些內容是: - [React API 參考](https://beta.reactjs.org/apis/react) 部分包含所有內容,以便更快地諮詢程式碼片段。 - “[聲明式 UI 與命令式 UI 相比如何](https://beta.reactjs.org/learn/reacting-to-input-with-state#how-declarative-ui-compares-to-imperative )”主題展示瞭如何更好地編寫聲明式 React 元件。 - “[Render and Commit](https://beta.reactjs.org/learn/render-and-commit)” 了解渲染 React 元件過程中的步驟。 - “[排隊一系列狀態更新](https://beta.reactjs.org/learn/queueing-a-series-of-state-updates)”主題將解釋為什麼有時它不起作用以及如何解決它. - “[通過自定義掛鉤重用邏輯](https://beta.reactjs.org/learn/reusing-logic-with-custom-hooks)”了解如何在元件之間共享邏輯。 ## 結論 **從基礎主題到進階主題,這些文檔涵蓋了您學習如何使用最好的現代 React 建立用戶界面所需的一切。**如果您是 React 世界的新手,本文檔肯定會對您有很大幫助互動式範例。對於經驗豐富的 React 開發人員,本文檔匯集了幾個重要的進階概念,這些概念一定會幫助您建立更好的 UI 元件。

20 個冷門、但很實用的 git 指令:值得你稍微認識一下

如果您曾經瀏覽過 [git 手冊](https://git-scm.com/docs)(或執行 `man git`),那麼您會發現 git 指令比我們每天在用的多很多。很多指令非常強大,可以讓你的生活更輕鬆(有些比較小眾,但知道一下還是不錯)。 > 這篇文章整理了我最喜歡的 20 個冷門 git 功能,您可以使用來改善您的開發流程、給您的同事留下深刻印象、幫助您回答 git 面試問題,最重要的是 - 可以玩得很開心! 原文出處:https://dev.to/lissy93/20-git-commands-you-probably-didnt-know-about-4j4o --- ## Git Web > 執行 [`git instaweb`](https://git-scm.com/docs/git-instaweb) 可以立即瀏覽 gitweb 中的工作存儲庫 Git 有一個內建的[基於網路可視化工具](https://git-scm.com/docs/gitweb) 可以瀏覽本地存儲庫,它允許您通過瀏覽器中的 GUI 查看和管理您的存儲庫。它包含許多有用的功能,包括: - 瀏覽和單步執行修訂並檢查差異、文件內容和元資料 - 可視化查看提交日誌、分支、目錄、文件歷史和附加資料 - 生成提交和存儲庫活動日誌的 RSS 或 Atom 提要 - 搜尋提交、文件、更改和差異 要打開它,只需從您的存儲庫中執行 `git instaweb`。您的瀏覽器應該會彈出並讀取 http://localhost:1234 。如果您沒有安裝 Lighttpd,您可以使用“-d”標誌指定一個備用 Web 伺服器。其他選項可以通過標誌配置(例如 `-p` 用於端口,`-b` 用於打開瀏覽器等),或在 git 配置中的 `[instaweb]` 塊下配置。 還有 `git gui` 命令,它可以打開一個基於 GUI 的 git 應用程式 ![](https://i.ibb.co/0DrmcWG/Screenshot-from-2022-12-17-20-26-30.png) --- ## Git Notes > 使用 [`git notes`](https://git-scm.com/docs/git-notes) 向提交加入額外訊息 有時您需要將其他資料附加到 git 提交(除了更改、訊息、日期時間和作者訊息之外)。 註釋存儲在 .git/refs/notes 中,由於它與提交對像資料是分開的,因此您可以隨時修改與提交關聯的註釋,而無需更改 SHA-1 哈希。 您可以使用 `git log`、使用大多數 git GUI 應用程式或使用 `git notes show` 命令查看筆記。一些 git 主機還在提交視圖中顯示註釋(儘管 [GH 不再顯示註釋](https://github.blog/2010-08-25-git-notes-display/))。 --- ## Git Bisect > 使用 [`git bisect`](https://git-scm.com/docs/git-bisect) 你可以使用二進制搜尋找到引入錯誤的提交 這是最強大又好用的 git 命令之一 - bisect 在除錯時絕對是救命稻草。開始對分後,它會為您檢查提交,然後您告訴它提交是“好”(沒有錯誤)還是“壞”(引入錯誤),這可以讓您縮小最早提交的錯誤。 請執行 `git bisect start`,然後使用 `git bisect good <commit-hash>` 向其傳遞一個已知的良好提交,並使用 `git bisect bad <optional-hash>` 傳遞一個已知的錯誤提交(預設為當前)。然後它會檢查好提交和壞提交之間的提交,然後你用 `git bisect good` 或 `git bisect bad` 指定錯誤存在與否。然後它會重複這個過程,在好與壞的中心檢查一個提交,一直到你找到引入錯誤的確切提交。隨時使用 `git bisect reset` 取消。 bisect 命令還有更多功能,包括回放、查看提交、跳過,因此下次除錯時值得查看文檔。 --- ## Git Grep > 使用 [`git grep`](https://git-scm.com/docs/git-grep) 在您的存儲庫中搜尋程式碼、文件、提交或任何其他內容 有沒有發現自己需要在 git 專案中的任何地方搜尋字串?使用 git grep,您可以輕鬆地在整個專案中和跨分支搜尋任何字串或 RegEx(例如更強大的 <kbd>Ctrl</kbd> + <kbd>F</kbd>!)。 `git grep <regexp> <ref>` 它包括大量 [選項](https://git-scm.com/docs/git-grep#_options) 來縮小搜尋範圍,或指定結果格式。例如,使用 `-l` 僅返回文件名,`-c` 指定每個文件返回的匹配數,`-e` 排除匹配條件的結果,`--and` 指定多個條件,` -n` 以行號搜尋。 由於 git grep 與正則表達式兼容,因此您可以使用搜尋的字串獲得更多進階訊息。 您還可以使用它來指定文件擴展名,例如 `git grep 'console.log' *.js`,它將顯示 JavaScript 文件中的所有 console.logs 第二個參數是一個 ref,可以是分支名稱、提交、提交範圍或其他任何內容。例如。 `git grep "foo" HEAD~1` 將搜尋之前的提交。 --- ## Git Archive > 使用 [`git archive`](https://git-scm.com/docs/git-archive) 將整個 repo 合併到一個文件中 共享或備份存儲庫時,通常首選將其存儲為單個文件。使用 git archive 將包括所有 repo 歷史記錄,因此可以輕鬆將其提取回其原始形式。該命令還包括許多附加選項,因此您可以準確自定義存檔中包含和不包含的文件。 ``` git archive --format=tar --output=./my-archive HEAD ``` --- ## Git Submodules > 使用 [`git submodule`](https://git-scm.com/docs/git-submodule) 將任何其他存儲庫拉入您的存儲庫 在 git 中,[submodules](https://git-scm.com/docs/gitsubmodules) 讓您可以將一個存儲庫掛載到另一個存儲庫中,通常用於核心依賴項或將組件拆分到單獨的存儲庫中。有關詳細訊息,請參閱[這篇文章](https://notes.aliciasykes.com/17996/quick-tip-git-submodules)。 執行以下命令會將模塊拉到指定位置,並建立一個 .gitmodules 文件,以便在複製 repo 時始終下載它。複製 repo 時使用 `--recursive` 標誌來包含子模塊。 ``` git submodule add https://github.com/<user>/<repo> <path/to/save/at> ``` 還有 [`git subtree`](https://www.atlassian.com/git/tutorials/git-subtree),它做類似的事情,但不需要元資料文件。 --- ## Git Bug Report > 使用 [`git bugreport`](https://git-scm.com/docs/git-bugreport) 編寫錯誤票,包括 git 和系統訊息 此命令將捕獲系統訊息,然後打開一個標準錯誤模板(重現步驟、實際 + 預期輸出等)。完成的文件應該是一個非常完整的錯誤報告,包含所有必要的訊息。 如果您是開源包的維護者並要求用戶(開發人員)提出錯誤報告,這將非常方便,因為它確保包含所有必要的資料。 如果您向核心 git 系統提交錯誤報告,您還可以執行 [`git diagnostic`](https://git-scm.com/docs/git-diagnose) 命令,然後提出您的問題 [這裡](https://github.com/git/git)。 --- ## Git Fsck > 使用 [`git fsck`](https://git-scm.com/docs/git-fsck) 檢查所有物件,或恢復無法存取的物件 雖然不常需要,但有時您可能必須驗證 git 存儲的物件。這就是 fsck(或文件系統檢查)發揮作用的地方,它測試對像資料庫並驗證所有物件的 SHA-1 ID 及其建立的連接。 它還可以與 `--unreachable` 標誌一起使用,以查找不再可以從任何命名引用存取的物件(因為與其他命令不同,它包括 `.git/objects` 中的所有內容)。 --- ## Git Stripspace > 使用 [`git stripspace`](https://git-scm.com/docs/git-stripspace) 格式化給定文件中的空格 最佳做法是避免在行尾尾隨空格,避免有多個連續的空行,避免輸入的開頭和結尾出現空行,並以新行結束每個文件。有很多特定於語言的工具可以自動為您執行此操作(例如 prettier),但 Git 也內置了此功能。 它用於元資料(提交訊息、標籤、分支描述等),但如果您將文件通過管道傳輸給它,然後將響應通過管道傳輸回文件,它也可以工作。例如。 `cat ./path-to-file.txt | git stripspace` 或 `git stripspace < dirty-file.txt > clean-file.txt` 您還可以使用它來刪除註釋(使用 `--strip-comments`),甚至註釋掉行(使用 `--comment-lines`)。 --- ## Git Diff > 使用 [`git diff`](https://git-scm.com/docs/git-diff) 你可以比較 2 組程式碼之間的差異 您可能知道您可以執行 `git diff` 來顯示自上次提交以來的所有更改,或者使用 `git diff <commit-sha>` 來比較 2 次提交或 1 次提交到 HEAD。但是您可以使用 diff 命令做更多的事情。 您還可以使用它來比較任意兩個任意文件,使用 `diff file-1.txt file-2.txt`(不再存取 [diffchecker.com](https://www.diffchecker.com/compare/)! ) 或者使用 `git diff branch1..branch2` 相互比較 2 個分支或引用 請注意,雙點 (`..`) 與空格相同,表示 diff 輸入應該是分支的尖端,但您也可以使用三點 (`...`) 來轉換第一個參數進入兩個差異輸入之間共享的共同祖先提交的引用 - 非常有用!如果只想跨分支比較單個文件,只需將文件名作為第三個參數傳遞。 您可能希望查看在給定日期範圍內所做的所有更改,為此使用 `git diff HEAD@{7.day.ago} HEAD@{0}`(上週),同樣可以將其與文件名、分支名稱、特定提交或任何其他參考。 還有 [`git range-diff`](https://www.git-scm.com/docs/git-range-diff) 命令,它提供了一個用於比較提交範圍的簡單界面。 git diff 工具還有更多功能(以及使用您自己的差異檢查器的選項),因此我建議查看 [文檔](https://git-scm.com/docs/git-diff#_description) . --- ## Git Hooks > 使用 [`hooks`](https://git-scm.com/docs/githooks) 在給定的 get 操作發生時執行命令或執行腳本 Hooks 可以讓你自動化幾乎所有的事情。例如:確保滿足標準(提交訊息、分支名稱、補丁大小)、程式碼質量(測試、lint)、將附加訊息附加到提交(用戶、設備、票證 ID)、呼叫 webhook 來記錄事件或執行管道等 對於大多數 git 事件,如 commit, rebase, merge, push, update, applypatch 等,都有前後 [hooks available](https://git-scm.com/docs/githooks)。 鉤子存儲在 `.git/hooks` 中(除非您使用 `git config core.hooksPath` 在其他地方配置它們),並且可以使用 [`git hook`](https://git-scm.com/docs) 進行測試/git-hook) 命令。由於它們只是 shell 文件,因此可用於執行任何命令。 掛鉤不會推送到遠程存儲庫,因此要在您的團隊中共享和管理它們,您需要使用 [掛鉤管理器](https://github.com/aitemr/awesome-git-hooks#tools) ,例如 [lefthook](https://github.com/evilmartians/lefthook) 或 [husky](https://github.com/typicode/husky)。還有幾個[3rd-party tools](https://githooks.com/#projects),這使得管理鉤子更容易,我推薦[overcommit](https://github.com/sds/overcommit)。 請記住,掛鉤總是可以跳過(使用 `--no-verify` 標誌),所以永遠不要純粹依賴掛鉤,尤其是對於任何與安全相關的事情。 --- ## Git Blame > 使用 [`git blame`](https://git-scm.com/docs/git-blame) 顯示特定修訂版和行的作者訊息 一個經典的,快速找出誰寫了特定程式碼行(也就是你的哪個同事應該為這個錯誤負責!)。但它也有助於確定在哪個時間點發生了某些更改並檢查該提交和關聯的元資料。 例如,要查看 index.rs 第 400 到 420 行的作者和提交訊息,您可以執行: ``` git blame -L 400,420 index.rs ``` --- ## Git LFS > 使用 [`git lfs`](https://git-lfs.github.com/) 存儲大文件,以免拖慢您的存儲庫 您的專案通常會包含較大的文件(例如資料庫、二進制資產、檔案或媒體文件),這會減慢 git 工作流程並使使用限制達到最大。這就是 [大型文件存儲](https://git-lfs.github.com/) 的用武之地 - 它使您能夠將這些大型資產存儲在其他地方,同時使它們可以通過 git 進行跟踪並保持相同的存取控制/權限。 LFS 的工作原理是將這些較大的文件替換為在 git 中跟踪的文本指針。 要使用它,只需執行 `git lfs track <file glob>`,這將更新您的 `.gitattributes` 文件。您可以通過擴展名(例如“*.psd”)、目錄或單獨指定文件。執行 git lfs ls-files 以查看跟踪的 LFS 文件列表。 --- ## Git GC > 使用 [`git gc`](https://git-scm.com/docs/git-gc) 優化您的存儲庫 隨著時間的推移,git repos 會積累各種類型的垃圾,這些垃圾會佔用磁盤空間並減慢操作速度。這就是內置垃圾收集器的用武之地。執行 `git gc` 將刪除孤立的和不可存取的提交(使用 [`git prune`](https://git-scm.com/docs/git-prune)),壓縮文件修訂和存儲的 git 物件,以及一些其他一般的內務管理任務,如打包引用、修剪引用日誌、尊重元資料或陳舊的工作樹和更新索引。 加入 `--aggressive` 標誌將 [積極優化](https://git-scm.com/docs/git-gc#_aggressive) 存儲庫,丟棄任何現有的增量並重新計算它們,這需要更長的時間執行但如果你有一個大型存儲庫可能需要。 --- ## Git Show > 使用 [`git show`](https://git-scm.com/docs/git-show) 輕鬆檢查任何 git 物件 以易於閱讀的形式輸出物件(blob、樹、標籤或提交)。要使用,只需執行 `git show <object>`。您可能還想附加 `--pretty` 標誌,以獲得更清晰的輸出,但還有許多其他選項可用於自定義輸出(使用 `--format`),因此此命令對於準確顯示非常強大你需要什麼。 這非常有用的一個實例是在另一個分支中預覽文件,而無需切換分支。只需執行 `git show branch:file` --- ## Git Describe > 使用 [`git describe`](https://git-scm.com/docs/git-describe) 查找可從提交中存取的最新標記,並為其指定一個人類可讀的名稱 執行 `git describe`,您將看到一個人類可讀的字串,該字串由最後一個標籤名稱與當前提交組合而成,以生成一個字串。您還可以將特定標籤傳遞給它, 請注意,您必須已建立標籤才能使其正常工作,除非您附加了 `--all` 標誌。默認情況下,Git describe 也只會使用帶註釋的標籤,因此您必須指定 `--tags` 標誌以使其也使用輕量級標籤。 --- ## Git Tag > 使用 [`git tag`](https://git-scm.com/docs/git-tag) 在你的 repo 歷史中標記一個特定點 能夠[標記](https://git-scm.com/book/en/v2/Git-Basics-Tagging) 存儲庫歷史記錄中最常用於表示發布版本的特定重要點通常很有用。建立標籤就像 `git tag <tagname>` 一樣簡單,或者您可以使用 `git tag -a v4.2.0 <commit sha>` 標記歷史提交。與提交一樣,您可以使用“-m”在標籤旁邊包含一條訊息。 不要忘記使用 `git push origin <tagname>` 將您的標籤推送到遠程。 要列出所有標籤,只需執行 `git tag`,並可選擇使用 `-l` 進行通配符搜尋。 然後,您將能夠使用 `git checkout <tagname>` 檢出特定標籤 --- ## Git Reflog > 使用 [`git reflog`](https://git-scm.com/docs/git-reflog) 列出對您的存儲庫所做的所有更新 Git 使用稱為參考日誌或“reflogs”的機制跟踪分支尖端的更新。跟踪各種事件,包括:克隆、拉取、推送、提交、檢出和合併。能夠找到事件引用通常很有用,因為許多命令都接受引用作為參數。只需執行 `git reflog` 即可查看 `HEAD` 上的最近事件。 reflog 真正有用的一件事是恢復丟失的提交。 Git 永遠不會真正丟失任何東西,即使是在重寫歷史時(比如變基或提交修改)。 Reflog 允許您返回提交,即使它們沒有被任何分支或標記引用。 默認情況下,reflog 使用 `HEAD`(您當前的分支),但您可以在任何 ref 上執行 reflog。例如 `git reflog show <branch name>`,或者使用 `git reflog stash` 查看隱藏的更改。或者使用 `git reflog show --all` 顯示所有引用 --- ## Git Log > 使用 [`git log`](https://git-scm.com/docs/git-log) 查看提交列表 您可能已經熟悉執行 `git log` 來查看當前分支上最近提交的列表。但是您可以使用 git log 做更多的事情。 使用 `git log --graph --decorate --oneline` 將顯示一個漂亮整潔的提交圖以及 ref 指針。 ![示例 git 日誌輸出](https://i.ibb.co/c1WByg8/Screenshot-from-2022-12-17-20-43-56.png) 您還經常需要能夠根據各種參數過濾日誌,其中最有用的是: - `git log --search="<anything>"` - 搜尋特定程式碼更改的日誌 - `git log --author="<pattern>"` - 只顯示特定作者的日誌 - `git log --grep="<pattern>"` - 使用搜尋詞或正則表達式過濾日誌 - `git log <since>..<until>` - 顯示兩個引用之間的所有提交 - `git log -- <file>` - 顯示僅對特定文件進行的所有提交 或者,只需執行 `git shortlog` 以獲得匯總的提交列表。 --- ## Git Cherry Pick > 使用 [`git cherry-pick`](https://git-scm.com/docs/git-cherry-pick) 通過引用選擇指定的提交並將它們附加到工作 HEAD 有時你需要從其他地方拉一個特定的提交到你當前的分支。這對於應用熱修復、撤消更改、恢復丟失的提交以及在某些團隊協作設置中非常有用。請注意,通常傳統的合併是更好的做法,因為挑選提交會導致日誌中出現重複提交。 用法很簡單,只需執行 `git cherry-pick <commit-hash>`。這會將指定的提交拉入當前分支。 --- ## Git Switch > 使用 [`git switch`](https://git-scm.com/docs/git-switch) 在分支之間移動是我們經常做的事情,`switch` 命令就像是`git checkout` 的簡化版本,它可以用來建立和在分支之間導航,但不像 checkout 在分支之間移動時不會復制修改的文件. 類似於 `checkout -b`,使用 switch 命令你可以附加 `-c` 標誌來建立一個新分支,然後直接跳入其中,例如`git switch -c <新分支>`。執行 `git switch -` 將放棄您所做的任何實驗性更改,並返回到您之前的分支。 --- ## Git Standup > 使用 [`git standup`](https://github.com/kamranahmedse/git-standup) 回憶你在最後一個工作日做了什麼,基於 git 提交 我把它放在最後,因為它不包含在大多數 git 客戶端中,但是您可以使用系統包管理器[輕鬆安裝](https://github.com/kamranahmedse/git-standup#install) ,使用 1 行 curl 腳本,或從源程式碼建置。 如果您的老闆要求您每天站立一次,以更新昨天的工作,但您永遠記不起自己到底做了什麼——這個適合您!它將顯示一個格式良好的列表,列出在給定時間範圍內完成的所有事情。用法很簡單,只需執行 `git standup`,或使用 [這些選項](https://github.com/kamranahmedse/git-standup#options) 指定應顯示哪些資料(作者、時間範圍、分支機構等)。 --- ## 結論 希望對您有幫助!

在 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 的簡單說明,希望對您有幫助。

寫出更好 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>; } ``` --- 以上是快速整理,希望對您有幫助!

React 生態系中,5個比較少見,但很好用的套件

我很喜歡在 NPM 目錄到處逛、尋找優質小套件。今天跟你分享五個我的近期發現! - 原文出處:https://dev.to/naubit/5-small-and-hidden-react-libraries-you-should-already-be-using-nb5 ## 1. Urlcat Urlcat 是一個小型的 Javascript 套件,可以非常方便地建立 URL、預防常見錯誤。 你當然可以直接用 URL API 來建立網址,但這種做法需要你手動處理一些細節。 Urlcat 就方便多了,隨插即用,不用花一堆時間讀文件,就能直接開始用。 https://github.com/balazsbotond/urlcat ## 2. UseHooks-ts ![](https://imgur.com/n7DL06Z.png) 如果你是 React 開發者、有在用 hook,很多時候你需要替一大堆小東西寫 custom hook。像是處理深色模式、處理視窗大小變化事件,等等。 UseHooks 是一個小套件,針對各種小案例都有現成的 hook,而且文件齊全、支援 TypeScript。 https://github.com/juliencrn/usehooks-ts ## 3. Logt ![](https://imgur.com/PU6eNCJ.gif) 我喜歡到處都有日誌,當需要知道發生了什麼時,就可以檢查。 當我寫前端時,**我也想要那些日誌**。但有一些先決條件: - 必須有完整的型別(這樣我就可以在 Typescript 中方便使用) - 必須很小 - 必須有彩色標籤(所以我很快就知道日誌類型) - 必須有分日誌級別 - 必須有一些方法,可以根據條件隱藏一些日誌(比如是否在正式環境) - 必須可以將這些日誌發送到其他地方(比如 Sentry) 經過大量時間研究(我都快自己開始寫了)我找到了 Logt,**它滿足我的所有要求**。 100% 推薦! https://github.com/sidhantpanda/logt ## 4. Loadable Components ![](https://imgur.com/H6eoKeF.png) 如果你正在嘗試優化 React 應用程式,**你可能正在使用 React.lazy** 和 Suspense 來延遲載入元件。 雖然也是可以,但還有更好的方法!比如這個套件。我無法在此完整說明原因,但請參考以下比較: https://loadable-components.com/docs/loadable-vs-react-lazy/ 基本上,它支持 **SSR**(_Server Side Rendering_)、**Library Splitting**,甚至 **完全動態導入**。還不錯吧? 此外,它真的很容易使用。**幾乎即插即用。**所以,試試吧! https://github.com/gregberge/loadable-components ## 5. Emoji Mart ![](https://imgur.com/jBA63Iu.png) 在處理不同的專案時,**我總是要處理表情符號。**現在到處都在使用它。而且我通常必須在專案中添加一些表情符號選擇器元件。 這還不算難。但是隨後開始收到更多要求:它必須**延遲載入表情符號**,它必須支持**國際化**,它必須允許**搜尋**,它必須允許使用**與 slack 相同的查詢縮寫**… 這些是可以做,但還是花時間在專案本身比較好吧。 所以,來使用 Emoji Mart 吧! https://github.com/missive/emoji-mart --- 以上是五個好用但是還不知名的小套件,希望你喜歡!

如何在 React 中漂亮地 render 一個列表:四點注意事項

面試的時候,常常會被問到這題。看似簡單,其實有一些進階注意事項,此篇與您分享。 - 原文出處:https://dev.to/andyrewlee/stand-out-in-a-react-interview-by-rendering-a-list-like-a-pro-1cn5 # 基本做法 以下是最基本做法。根據陣列內容,直接渲染成一個列表。 ``` import { useState, useEffect } from "react"; const App = () => { const [posts, setPosts] = useState([]); const [currentPost, setCurrentPost] = useState(undefined); useEffect(() => { const initialize = async () => { const res = await fetch("https://jsonplaceholder.typicode.com/posts"); const json = await res.json(); setPosts(json); }; initialize(); }, []); const onPostClick = (post) => { setCurrentPost(post); }; return ( <div> {currentPost && <h1>{currentPost.title}</h1>} <PostList posts={posts} onPostClick={onPostClick} /> </div> ); }; const PostList = ({ posts, onPostClick }) => { return ( <div> {posts.map((post) => ( <Post post={post} onPostClick={onPostClick} /> ))} </div> ); }; const Post = ({ post, onPostClick }) => { const onClick = () => { onPostClick(post); }; return <div onClick={onClick}>{post.title}</div>; }; export default App; ``` # 改進方法 以下是四個可以改進的方向,以及背後的原因。 ## 1. 指定 key 替每個元件提供一個 key 屬性,可以幫助後續 React 渲染時改善效能。要注意 key 屬性要是唯一值,不要直接用陣列索引當成 key。 ``` {posts.map((post) => ( <Post key={post.id} post={post} onPostClick={onPostClick} /> ))} ``` ## 2. 優化渲染 每次點擊列表項目時,都會重新渲染 `PostList` 和每個 `Post`。 ``` const Post = ({ post, onPostClick }) => { console.log("post rendered"); const onClick = () => { onPostClick(post); }; return <div onClick={onClick}>{post}</div>; }; ``` 可以使用 React 提供的 `memo` 功能來優化 `PostList` 元件。用 `memo` 包裝元件時,等於告訴 React:除非 props 改變,否則不要重新渲染這個元件。 ``` import { useState, useEffect, memo } from "react"; const PostList = memo(({ posts, onPostClick }) => { return ( <div> {posts.map((post) => ( <Post post={post} onPostClick={onPostClick} /> ))} </div> ); }); ``` 不過,實際跑下去,會發現還是重新渲染了。因為每次 currentPost 改變時,App 都會重新渲染。每次重新渲染都會重新建立 onPostClick 函數。當一個函數被重新建立時(即使函式內容一樣),都算是新的實體。所以技術上來說,props 確實發生了變化,所以 `PostList` 會重新渲染。 ``` const fn1 = () => {}; const fn2 = () => {}; fn1 === fn2; // => false ``` 這種狀況,就可以使用 useCallback hook 來告訴 React 不要重新建立函數。 ``` const onPostClick = useCallback((post) => { setCurrentPost(post); }, []); ``` 上面的例子中,使用 useCallback 沒問題,可以避免全部貼文被重新渲染。但要知道的是,並非什麼函式都適合包在 useCallback 裡面。 ``` const Post = ({ post, onPostClick }) => { const useCalllback(onClick = () => { onPostClick(post); }, []); return <div onClick={onClick}>{post.title}</div>; }; ``` 比方說,在 Post 元件使用 useCallback 就不太有意義。因為這個元件是輕量級的。應該只在有意義的情況下使用 useCallback(可以用 profiling 工具分析效能確認)。`useCallback` 有缺點:它增加了程式碼的複雜性。使用 useCallback 會在每次渲染時運行的額外程式碼。 ## 3. 元件卸載時清理乾淨 目前的元件沒有在卸載時進行清理。例如,如果在收到 URL 回應結果之前就離開頁面怎麼辦?這時應該要取消請求。 ``` useEffect(() => { const initialize = async () => { const res = await fetch("https://jsonplaceholder.typicode.com/posts"); const json = await res.json(); setPosts(json); }; initialize(); }, []); ``` `useEffect` 可以分為兩部分:掛載時運行的程式碼、卸載時運行的程式碼: ``` useEffect(() => { // When component mounts what code should I run? return () => { // When component unmounts what code should I run (clean up)? }; }, []); ``` 我們可以使用 AbortController ,並在清理時呼叫 controller.abort() 來取消請求。 ``` useEffect(() => { const controller = new AbortController(); const signal = controller.signal; const initialize = async () => { try { const res = await fetch("https://jsonplaceholder.typicode.com/posts", { signal }); const json = await res.json(); setPosts(json); } catch (err) { console.log(err); } }; initialize(); return () => { controller.abort(); }; }, []); ``` ## 4. 增加無障礙輔助功能 以上範例太過簡單,沒有太多無障礙功能可以加入。一旦應用程式變複雜,絕對應該要開始考慮這點。 有個簡單的無障礙測試:可以單獨只使用鍵盤就操作一個應用程式嗎? 關於這點,快速解法是:把每個項目都轉成按鈕,用鍵盤時就可以在元件之間切換。 ``` const Post = ({ post, onPostClick }) => { const onClick = () => { onPostClick(post); }; return <button onClick={onClick}>{post}</button>; }; ``` # 結論 在 React 中渲染列表,乍看之下,只是個簡單的面試問題。但其實可深可淺。下次面試時遇到這問題,可以思考一下此篇文章談到的各個面向。

開發 React 時,推薦使用這些 Best Practices

在開發 React App 時,遵循一些 best practices 會使您的程式碼品質提高,這篇文章列出一些給您參考。 - 原文出處:https://dev.to/iambilalriaz/react-best-practices-ege # 強烈推薦 VS Code 作為 IDE Visual Studio Code 有幾個超好用的 React 功能。強大的外掛生態系,對開發者大有幫助: - Prettier - ES Lint - JavaScript (ES6) code snippets - Reactjs code snippets - Auto import # 使用 ES6 語法 程式碼越漂亮越好。在 JavaScript 中,採用 ES6 語法可以讓程式碼更簡潔。 ## Arrow Functions ``` // ES5 function getSum(a, b) { return a + b; } // ES6 const getSum = (a, b) => a + b; ``` ## Template Literal ``` // ES5 var name = "Bilal"; console.log("My name is " + name); // ES6 const name = "Bilal"; console.log(`My name is ${name}`); ``` ## const $ let const $ let 有各自的變數作用域。const 宣告的變數不能修改,let 宣告的變數可以修改。 ``` // ES5 var fruits = ["apple", "banana"]; // ES6 let fruits = ["apple", "banana"]; fruits.push("mango"); const workingHours = 8; ``` ## Object Destructuring ``` var person = { name: "John", age: 40, }; // ES5 var name = person.name; var age = person.age; // ES6 const { name, age } = person; ``` ## Defining Objects ``` var name = "John"; var age = 40; var designations = "Full Stack Developer"; var workingHours = 8; // ES5 var person = { name: name, age: age, designation: designation, workingHours: workingHours, }; // ES6 const person = { name, age, designation, workingHours }; ``` ES6 的語法特性、彈性,很多值得您一試。 # JSX 使用 map 時記得加上 key array map 時,永遠記得替每個元素加上獨立的 key 值。 ``` const students = [{id: 1, name: 'Bilal'}, {id: 2, name: 'Haris'}]; // in return function of component <ul> {students.map(({id, name}) => ( <li key={id}>{name}</li> ))} </ul>; ``` # 元件名稱使用 PascalCase ``` const helloText = () => <div>Hello</div>; // wrong const HelloText = () => <div>Hello</div>; // correct ``` # 變數和函數名稱使用 camelCase ``` const working_hours = 10; // bad approach const workingHours = 10; // good approach const get_sum = (a, b) => a + b; // bad approach const getSum = (a, b) => a + b; // good approach ``` # ID 和 css class 名稱使用 kebab-case ``` <!--bad approach--> <div className="hello_word" id="hello_world">Hello World</div> <!--good approach --> <div className="hello-word" id="hello-world">Hello World</div> ``` # 永遠要檢查物件&陣列的 null & undefined 忘記檢查的話,常常會導致一堆錯誤。 所以要保持檢查的習慣。 ``` const person = { name: "Haris", city: "Lahore", }; console.log("Age", person.age); // error console.log("Age", person.age ? person.age : 20); // correct console.log("Age", person.age ?? 20); //correct const oddNumbers = undefined; console.log(oddNumbers.length); // error console.log(oddNumbers.length ? oddNumbers.length : "Array is undefined"); // correct console.log(oddNumbers.length ?? "Array is undefined"); // correct ``` # 避免 Inline Styling Inline styling 會讓 jsx 程式碼變得很亂。用單獨的 css 文件拆分出來比較好。 ``` const text = <div style={{ fontWeight: "bold" }}>Happy Learing!</div>; // bad approach const text = <div className="learning-text">Happy Learing!</div>; // good approach ``` 在 .css 文件中: ``` .learning-text { font-weight: bold; } ``` # 避免 DOM 操作 用 React state 為主,別用 DOM 操作 糟糕做法: ``` <div id="error-msg">Please enter a valid value</div> ``` ``` document.getElementById("error-msg").visibility = visible; ``` 推薦做法: ``` const [isValid, setIsValid] = useState(false); <div hidden={isValid}>Please enter a valid value</div>; ``` 使用 isValid 來管理 UI 顯示邏輯。 # 在 useEffect 記得清乾淨每個事件監聽器 加過的事件監聽器,都要記得清乾淨: ``` const printHello = () => console.log("HELLO"); useEffect(() => { document.addEventListener("click", printHello); return () => document.removeEventListener("click", printHello); }); ``` # 避免重複開發,多寫通用元件 讓程式碼越乾淨越好。相似的東西可以寫通用元件。再根據 props 內容傳遞來處理相異處即可: ``` const Input=(props)=>{ const [inputValue, setInputValue]=useState(''); return( <label>{props.thing}</label> <input type='text' value={inputValue} onChange={(e)=>setInputValue(e.target.value)} /> ) } ``` 在其他元件中,就能這樣用: ``` <div> <Input thing="First Name" /> <Input thing="Second Name" /> </div> ``` # 檔案要分類一下 相關檔案可以分類成一個資料夾。 例如在 React 寫一個導覽列,那就可以開一個資料夾,相關的 .js 與 .css 檔案放裡面。 # 寫 functional components 為主 簡單顯示一些東西、沒用到 state 的話,那寫 functional components 比寫 class components 好。 如果你會寫 react hooks 的話,那就連 state 都完全不成問題。 # 養成編寫輔助函數的習慣 有時你在 React App 中會需要一些通用功能。 這種情況,可以開一個 `helper-functions.js` 檔案,在裡面寫輔助函數,就可以到處使用了。 ## 使用三元運算子代替 if/else if 使用 `if/else if` 語句會使程式碼變得龐大。使用三元運算子,就簡潔、清楚多了: ``` // Bad approach if (name === "Ali") { return 1; } else if (name === "Bilal") { return 2; } else { return 3; } // Good approach name === "Ali" ? 1 : name === "Bilal" ? 2 : 3; ``` # 新增 index.js 檔案,讓匯入元件更簡單 如果你在 actions 資料夾中有一個 index.js 檔案,當你想在元件中導入時,會像這樣: ``` import { actionName } from "src/redux/actions"; ``` actions 後面的 index.js 可以省略不寫,就不用這樣囉唆了: ``` import { actionName } from "src/redux/actions/index"; ``` # Destructuring of Props 物件屬性名稱可以拆出來,後面用起來比較方便。 假設你的元件有 `name`、`age` 和 `designation` 這些 props: ``` // Bad approach const Details = (props) => { return ( <div> <p>{props.name}</p> <p>{props.age}</p> <p>{props.designation}</p> </div> ); }; // Good approach const Details = ({ name, age, designation }) => { return ( <div> <p>{name}</p> <p>{age}</p> <p>{designation}</p> </div> ); }; ``` # 不要嘗試在同一函數中,去碰修改過的 state 變數 在一個函數中,如果你正在為一個狀態變數賦值,在同一個函數中,是拿不到新值的 ``` const Message = () => { const [message, setMessage] = useState("Hello World"); const changeMessage = (messageText) => { setMessage("Happy Learning"); console.log(message); // It will print Hello World on console }; return <div>{message}</div>; }; ``` # 使用 === 運算子代替 == 在比較兩個值時,嚴格檢查變數型別比較好: ``` "2" == 2 ? true : false; // true "2" === 2 ? true : false; // false ``` --- 以上 Best Practices 供您參考,祝福您不斷變強!