🔍 搜尋結果:fetch

🔍 搜尋結果:fetch

44 個 React 前端面試問題

原文出處:https://dev.to/m_midas/44-react-frontend-interview-questions-2o63 ## 介紹 在面試 React 前端開發人員職位時,為技術問題做好充分準備至關重要。 React 已經成為建立使用者介面最受歡迎的 JavaScript 程式庫之一,雇主通常專注於評估候選人對 React 核心概念、最佳實踐和相關技術的理解。在本文中,我們將探討 React 前端開發人員面試期間常見問題的完整清單。透過熟悉這些問題及其答案,您可以增加成功的機會並展示您在 React 開發方面的熟練程度。因此,讓我們深入探討您應該準備好在 React 前端開發人員面試中解決的關鍵主題。 ![](https://media.giphy.com/media/AYECTMLNS4o67dCoeY/giphy.gif) ### 1.你知道哪些React hooks? - `useState`:用於管理功能元件中的狀態。 - `useEffect`:用於在功能元件中執行副作用,例如取得資料或訂閱事件。 - `useContext`:用於存取功能元件內的 React 上下文的值。 - `useRef`:用於建立對跨渲染持續存在的元素或值的可變引用。 - `useCallback`:用於記憶函數以防止不必要的重新渲染。 - `useMemo`:用於記憶值,透過快取昂貴的計算來提高效能。 - `useReducer`:用於使用reducer函數管理狀態,類似於Redux的工作方式。 - `useLayoutEffect`:與 useEffect 類似,但效果在所有 DOM 變更後同步運作。 這些鉤子提供了強大的工具來管理狀態、處理副作用以及重複使用 React 功能元件中的邏輯。 [了解更多](https://react.dev/reference/react) ### 2.什麼是虛擬 DOM? 虛擬 DOM 是 React 中的一個概念,其中建立實際 DOM(文件物件模型)的輕量級虛擬表示並將其儲存在記憶體中。它是一種用於優化 Web 應用程式效能的程式設計技術。 當 React 元件的資料或狀態發生變更時,虛擬 DOM 會被更新,而不是直接操作真實 DOM。然後,虛擬 DOM 計算元件的先前狀態和更新狀態之間的差異,稱為「比較」過程。 一旦辨識出差異,React 就會有效地僅更新真實 DOM 的必要部分以反映變更。這種方法最大限度地減少了實際 DOM 操作的數量,並提高了應用程式的整體效能。 透過使用虛擬 DOM,React 提供了一種建立動態和互動式使用者介面的方法,同時確保最佳效率和渲染速度。 ### 3. 如何渲染元素陣列? 要渲染元素陣列,可以使用“map()”方法迭代該陣列並傳回一個新的 React 元素陣列。 ``` const languages = [ "JavaScript", "TypeScript", "Python", ]; function App() { return ( <div> <ul>{languages.map((language) => <li>{language}</li>)}</ul> </div> ); } ``` [了解更多](https://react.dev/learn/rendering-lists) ### 4. 受控元件和非受控元件有什麼不同? 受控元件和非受控元件之間的區別在於**它們如何管理和更新其狀態**。 受控元件是狀態由 React 控制的元件。元件接收其當前值並透過 props 更新它。當值改變時它也會觸發回調函數。這意味著該元件不儲存其自己的內部狀態。相反,父元件管理該值並將其傳遞給受控元件。 ``` import { useState } from 'react'; function App() { const [value, setValue] = useState(''); return ( <div> <h3>Controlled Component</h3> <input name="name" value={name} onChange={(e) => setValue(e.target.value)} /> <button onClick={() => console.log(value)}>Get Value</button> </div> ); } ``` 另一方面,不受控制的元件使用 refs 或其他方法在內部管理自己的狀態。它們獨立儲存和更新狀態,不依賴 props 或回呼。父元件對不受控元件的狀態控制較少。 ``` import { useRef } from 'react'; function App() { const inputRef = useRef(null); return ( <div className="App"> <h3>Uncontrolled Component</h3> <input type="text" name="name" ref={inputRef} /> <button onClick={() => console.log(inputRef.current.value)}>Get Value</button> </div> ); } ``` [了解更多](https://react.dev/learn/sharing-state- Between-components#driven-and-uncontrol-components) ### 5. 基於類別的 React 元件和函數式 React 元件有什麼不同? 基於類別的元件和函數式元件之間的主要區別在於**它們的定義方式以及它們使用的語法。** 基於類別的元件被定義為 ES6 類別並擴展了 `React.Component` 類別。他們使用「render」方法傳回定義元件輸出的 JSX (JavaScript XML)。類別元件可以透過「this.state」和「this.setState()」存取元件生命週期方法和狀態管理。 ``` class App extends React.Component { state = { value: 0, }; handleAgeChange = () => { this.setState({ value: this.state.value + 1 }); }; render() { return ( <> <p>Value is {this.state.value}</p> <button onClick={this.handleAgeChange}> Increment value </button> </> ); } } ``` 另一方面,函數元件被定義為簡單的 JavaScript 函數。他們接受 props 作為參數並直接返回 JSX。功能元件無權存取生命週期方法或狀態。然而,隨著 React 16.8 中 React Hooks 的引入,功能元件現在可以管理狀態並使用其他功能,例如上下文和效果。 ``` import { useState } from 'react'; const App = () => { const [value, setValue] = useState(0); const handleAgeChange = () => { setValue(value + 1); }; return ( <> <p>Value is {value}</p> <button onClick={handleAgeChange}> Increment value </button> </> ); } ``` 一般來說,功能元件被認為更簡單、更容易閱讀和測試。建議盡可能使用函數式元件,除非有特定需要基於類別的元件。 ### 6. 元件的生命週期方法有哪些? 生命週期方法是一種掛鉤元件生命週期不同階段的方法,可讓您在特定時間執行特定程式碼。 以下是主要生命週期方法的清單: 1. `constructor`:這是建立元件時呼叫的第一個方法。它用於初始化狀態和綁定事件處理程序。在功能元件中,您可以使用“useState”鉤子來實現類似的目的。 2. `render`:此方法負責渲染 JSX 標記並傳回螢幕上要顯示的內容。 3. `componentDidMount`:元件在 DOM 中渲染後立即呼叫該方法。它通常用於初始化任務,例如 API 呼叫或設定事件偵聽器。 4. `componentDidUpdate`:當元件的 props 或 state 改變時呼叫該方法。它允許您執行副作用、根據更改更新元件或觸發其他 API 呼叫。 5. `componentWillUnmount`:在元件從 DOM 刪除之前呼叫此方法。它用於清理在`componentDidMount`中設定的任何資源,例如刪除事件偵聽器或取消計時器。 一些生命週期方法,例如“componentWillMount”、“componentWillReceiveProps”和“componentWillUpdate”,已被棄用或替換為替代方法或掛鉤。 至於“this”,它指的是類別元件的當前實例。它允許您存取元件內的屬性和方法。在函數式元件中,不使用“this”,因為函數未綁定到特定實例。 ### 7. 使用 useState 有什麼特色? `useState` 傳回一個狀態值和一個更新它的函數。 ``` const [value, setValue] = useState('Some state'); ``` 在初始渲染期間,傳回的狀態與作為第一個參數傳遞的值相符。 `setState` 函數用於更新狀態。它採用新的狀態值作為參數,並**對元件的重新渲染進行排隊**。 `setState` 函數也可以接受回呼函數作為參數,該函數將先前的狀態值作為參數。 [了解更多](https://react.dev/reference/react/useState) ### 8. 使用 useEffect 有什麼特別之處? `useEffect` 鉤子可讓您在功能元件中執行副作用。 稱為 React 渲染階段的功能元件的主體內部不允許突變、訂閱、計時器、日誌記錄和其他副作用。這可能會導致用戶介面中出現令人困惑的錯誤和不一致。 相反,建議使用 useEffect。傳遞給 useEffect 的函數將在渲染提交到螢幕後執行,或者如果您傳遞一組依賴項作為第二個參數,則每次依賴項之一發生變更時都會呼叫該函數。 ``` useEffect(() => { console.log('Logging something'); }, []) ``` [了解更多](https://react.dev/reference/react/useEffect) ### 9. 如何追蹤功能元件的卸載? 通常,「useEffect」會建立在元件離開畫面之前需要清理或重設的資源,例如訂閱或計時器辨識碼。 為了做到這一點,傳遞給`useEffect`的函數可以傳回一個**清理函數**。清理函數在元件從使用者介面刪除之前執行,以防止記憶體洩漏。此外,如果元件渲染多次(通常是這種情況),則在執行下一個效果之前會清除上一個效果。 ``` useEffect(() => { function handleChange(value) { setValue(value); } SomeAPI.doFunction(id, handleChange); return function cleanup() { SomeAPI.undoFunction(id, handleChange); }; }) ``` ### 10. React 中的 props 是什麼? Props 是從父元件傳遞給元件的資料。道具 是唯讀的,無法更改。 ``` // Parent component const Parent = () => { const data = "Hello, World!"; return ( <div> <Child data={data} /> </div> ); }; // Child component const Child = ({ data }) => { return <div>{data}</div>; }; ``` [了解更多](https://react.dev/learn/passing-props-to-a-component) ### 11. 什麼是狀態管理器?您曾與哪些狀態管理器合作過或認識哪些狀態管理器? 狀態管理器是幫助管理應用程式狀態的工具或程式庫。它提供了一個集中式儲存或容器來儲存和管理可由應用程式中的不同元件存取和更新的資料。 狀態管理器可以解決幾個問題。首先,將資料和與其相關的邏輯與元件分開是一個很好的做法。其次,當使用本機狀態並在元件之間傳遞它時,由於元件可能存在深層嵌套,程式碼可能會變得複雜。透過擁有全域存儲,我們可以存取和修改來自任何元件的資料。 除了 React Context,Redux 或 MobX 通常用作狀態管理庫。 [了解更多](https://mobx.js.org/README.html) [了解更多](https://redux-toolkit.js.org/) ### 12. 在什麼情況下可以使用本地狀態,什麼時候應該使用全域狀態? 如果本機狀態僅在一個元件中使用且不打算將其傳遞給其他元件,則建議使用本機狀態。本地狀態也用在表示清單中單一專案的元件中。但是,如果元件分解涉及嵌套元件且資料沿層次結構傳遞,則最好使用全域狀態。 ### 13. Redux中的reducer是什麼,它需要哪些參數? 減速器是一個純函數,它將狀態和操作作為參數。在減速器內部,我們追蹤接收到的操作的類型,並根據它修改狀態並傳回一個新的狀態物件。 ``` export default function appReducer(state = initialState, action) { // The reducer normally looks at the action type field to decide what happens switch (action.type) { // Do something here based on the different types of actions default: // If this reducer doesn't recognize the action type, or doesn't // care about this specific action, return the existing state unchanged return state } } ``` [了解更多](https://redux.js.org/tutorials/fundamentals/part-3-state-actions-reducers) ### 14. 什麼是操作以及如何更改 Redux 中的狀態? Action 是一個簡單的 JavaScript 物件,必須有一個字段 一種。 ``` { type: "SOME_TYPE" } ``` 您也可以選擇新增一些資料作為**有效負載**。為了 改變狀態,需要呼叫我們傳遞給它的調度函數 行動 ``` { type: "SOME_TYPE", payload: "Any payload", } ``` [了解更多](https://redux.js.org/tutorials/fundamentals/part-3-state-actions-reducers) ### 15. Redux 實作了哪一種模式? Redux 實作了 **Flux 模式**,這是應用程式可預測的狀態管理模式。它透過引入單向資料流和應用程式狀態的集中儲存來幫助管理應用程式的狀態。 [了解更多](https://www.newline.co/fullstack-react/30-days-of-react/day-18/#:~:text=Flux%20is%20a%20pattern%20for,default% 20method %20用於%20處理%20資料。) ### 16. Mobx 實作哪一種模式? Mobx 實作了**觀察者模式**,也稱為發布-訂閱模式。 [了解更多](https://www.patterns.dev/posts/observer-pattern) ### 17. 使用 Mobx 的特徵是什麼? Mobx 提供了「observable」和「compulated」等裝飾器來定義可觀察狀態和反應函數。以action修飾的動作用於修改狀態,確保追蹤所有變更。 Mobx 還提供自動依賴追蹤、不同類型的反應、對反應性的細粒度控制,以及透過 mobx-react 套件與 React 無縫整合。總體而言,Mobx 透過根據可觀察狀態的變化自動執行更新過程來簡化狀態管理。 ### 18.如何存取Mobx狀態下的變數? 您可以透過使用「observable」裝飾器將變數定義為可觀察來存取狀態中的變數。這是一個例子: ``` import { observable, computed } from 'mobx'; class MyStore { @observable myVariable = 'Hello Mobx'; @computed get capitalizedVariable() { return this.myVariable.toUpperCase(); } } const store = new MyStore(); console.log(store.capitalizedVariable); // Output: HELLO MOBX store.myVariable = 'Hi Mobx'; console.log(store.capitalizedVariable); // Output: HI MOBX ``` 在此範例中,使用“observable”裝飾器將“myVariable”定義為可觀察物件。然後,您可以使用“store.myVariable”存取該變數。對「myVariable」所做的任何變更都會自動觸發相關元件或反應的更新。 [了解更多](https://mobx.js.org/actions.html) ### 19.Redux 和 Mobx 有什麼差別? Redux 是一個更簡單、更固執己見的狀態管理庫,遵循嚴格的單向資料流並促進不變性。它需要更多的樣板程式碼和顯式更新,但與 React 具有出色的整合。 另一方面,Mobx 提供了更靈活、更直觀的 API,且樣板程式碼更少。它允許您直接修改狀態並自動追蹤更改以獲得更好的性能。 Redux 和 Mobx 之間的選擇取決於您的特定需求和偏好。 ### 20.什麼是 JSX? 預設情況下,以下語法用於在 React 中建立元素。 ``` const someElement = React.createElement( 'h3', {className: 'title__value'}, 'Some Title Value' ); ``` 但我們已經習慣這樣看 ``` const someElement = ( <h3 className='title__value'>Some Title Value</h3> ); ``` 這正是標記所謂的 jsx。這是一種語言的擴展 簡化對程式碼和開發的認知 [了解更多](https://react.dev/learn/writing-markup-with-jsx#jsx-putting-markup-into-javascript) ### 21.什麼是道具鑽探? Props 鑽取是指透過多層嵌套元件傳遞 props 的過程,即使某些中間元件不直接使用這些 props。這可能會導致程式碼結構複雜且繁瑣。 ``` // Parent component const Parent = () => { const data = "Hello, World!"; return ( <div> <ChildA data={data} /> </div> ); }; // Intermediate ChildA component const ChildA = ({ data }) => { return ( <div> <ChildB data={data} /> </div> ); }; // Leaf ChildB component const ChildB = ({ data }) => { return <div>{data}</div>; }; ``` 在此範例中,「data」屬性從 Parent 元件傳遞到 ChildA,然後從 ChildA 傳遞到 ChildB,即使 ChildA 不會直接使用該屬性。當存在許多層級的嵌套或當元件樹中更靠下的元件需要存取資料時,這可能會成為問題。它會使程式碼更難維護和理解。 可以透過使用其他模式(如上下文或狀態管理庫(如 Redux 或 MobX))來緩解 Props 鑽探。這些方法允許元件存取資料,而不需要透過每個中間元件傳遞 props。 ### 22. 如何有條件地渲染元素? 您可以使用任何條件運算符,包括三元。 ``` return ( <div> {isVisible && <span>I'm visible!</span>} </div> ); ``` ``` return ( <div> {isOnline ? <span>I'm online!</span> : <span>I'm offline</span>} </div> ); ``` ``` if (isOnline) { element = <span>I'm online!</span>; } else { element = <span>I'm offline</span>; } return ( <div> {element} </div> ); ``` [了解更多](https://react.dev/learn/conditional-rendering) ### 23. useMemo 的用途是什麼?它是如何運作的? `useMemo` 用於緩存和記憶 計算結果。 傳遞建立函數和依賴項陣列。只有當任何依賴項的值發生變更時,`useMemo` 才會重新計算記憶值。此優化有助於避免 每次渲染都需要昂貴的計算。 使用第一個參數,函數接受執行計算的回調,使用第二個依賴項陣列,僅當至少一個依賴項發生變更時,該函數才會重新執行計算。 ``` const memoValue = useMemo(() => computeFunc(paramA, paramB), [paramA, paramB]); ``` [了解更多](https://react.dev/reference/react/useMemo) ### 24. useCallback 的用途是什麼?它是如何運作的? `useCallback` 掛鉤將傳回回呼的記憶版本,僅當依賴項之一的值發生變更時,該版本才會變更。 當將回調傳遞給依賴連結相等性來防止不必要的渲染的最佳化子元件時,這非常有用。 ``` const callbackValue = useCallback(() => computeFunc(paramA, paramB), [paramA, paramB]); ``` [了解更多](https://react.dev/reference/react/useCallback) ### 25. useMemo 和 useCallback 有什麼不同? 1. `useMemo` 用於儲存計算結果,而 `useCallback` 用於儲存函數本身。 2. `useMemo` 快取計算值,如果依賴項沒有改變,則在後續渲染時傳回它。 3. `useCallback` 快取函數本身並傳回相同的實例,除非相依性發生變更。 ### 26.什麼是 React Context? React Context 是一項功能,它提供了一種透過元件樹傳遞資料的方法,而無需在每個層級手動傳遞 props。它允許您建立一個全域狀態,樹中的任何元件都可以存取該狀態,無論其位置如何。當您需要在未透過 props 直接連接的多個元件之間共用資料時,上下文就非常有用。 React Context API 由三個主要部分組成: 1. `createContext`:此函數用於建立一個新的上下文物件。 2. `Context.Provider`:該元件用於向上下文提供值。它包裝了需要存取該值的元件。 3. `Context.Consumer` 或 `useContext` 鉤子:此元件或鉤子用於使用上下文中的值。它可以在上下文提供者內的任何元件中使用。 透過使用 React Context,您可以避免道具鑽探(透過多個層級的元件傳遞道具)並輕鬆管理更高層級的狀態,使您的程式碼更有組織性和效率。 [了解更多](https://react.dev/learn/passing-data-deeply-with-context) ### 27. useContext 的用途是什麼?它是如何運作的? 在典型的 React 應用程式中,資料使用 props 從上到下(從父元件到子元件)傳遞。但這樣的使用方法對於某些類型的道具來說可能過於繁瑣 (例如,所選語言、UI 主題),必須傳遞給應用程式中的許多元件。上下文提供了一種在元件之間共享此類資料的方法,而無需明確傳遞 props 樹的每一層。 呼叫 useContext 的元件將始終在以下情況下重新渲染: 上下文值發生變化。如果重新渲染元件的成本很高,您可以使用記憶來優化它。 ``` const App = () => { const theme = useContext(ThemeContext); return ( <div style={{ color: theme.palette.primary.main }}> Some div </div> ); } ``` [了解更多](https://react.dev/reference/react/useContext) ### 28. useRef 的用途是什麼?它是如何運作的? `useRef` 傳回一個可修改的 ref 物件,一個屬性。其中的當前值由傳遞的參數初始化。傳回的物件將在元件的整個生命週期內持續存在,並且不會因渲染而改變。 通常的用例是以命令式存取後代 風格。 IE。使用 ref,我們可以明確引用 DOM 元素。 ``` const App = () => { const inputRef = useRef(null); const buttonClick = () => { inputRef.current.focus(); } return ( <> <input ref={inputRef} type="text" /> <button onClick={buttonClick}>Focus on input tag</button> </> ) } ``` [了解更多](https://react.dev/reference/react/useRef) ### 29. 什麼是 React.memo()? `React.memo()` 是一個高階元件。如果您的元件始終使用不變的 props 渲染相同的內容,您可以將其包裝在「React.memo()」呼叫中,以在某些情況下提高效能,從而記住結果。這意味著 React 將使用上次渲染的結果,避免重新渲染。 `React.memo()` 只影響 props 的變更。如果一個功能元件被包裝在 React.memo 中並使用 useState、useReducer 或 useContext,那麼當狀態或上下文發生變化時,它將重新渲染。 ``` import { memo } from 'react'; const MemoComponent = memo(MemoComponent = (props) => { // ... }); ``` [了解更多](https://react.dev/reference/react/memo) ### 30.React Fragment是什麼? 從元件傳回多個元素是 React 中的常見做法。片段可讓您形成子元素列表,而無需在 DOM 中建立不必要的節點。 ``` <> <OneChild /> <AnotherChild /> </> // or <React.Fragment> <OneChild /> <AnotherChild /> </React.Fragment> ``` [了解更多](https://react.dev/reference/react/Fragment) ### 31.什麼是 React Reconciliation? 協調是一種 React 演算法,用於區分一棵元素樹與另一棵元素樹,以確定需要替換的部分。 協調是我們過去所說的虛擬 DOM 背後的演算法。這個定義聽起來是這樣的:當你渲染一個 React 應用程式時,描述該應用程式的元素樹是在保留的記憶體中產生的。然後這棵樹被包含在渲染環境中——例如,瀏覽器應用程式,它被翻譯成一組 DOM 操作。當應用程式狀態更新時,會產生一棵新樹。將新樹與前一棵樹進行比較,以便準確計算並啟用重繪更新的應用程式所需的操作。 [了解更多](https://react.dev/learn/preserving-and-resetting-state) ### 32.為什麼使用map()時需要列表中的鍵? 這些鍵可幫助 React 確定哪些元素已更改, 新增或刪除。必須指定它們以便 React 可以匹配 隨著時間的推移陣列元素。選擇鍵的最佳方法是使用能夠清楚區分清單專案與其鄰居的字串。大多數情況下,您將使用資料中的 ID 作為金鑰。 ``` const languages = [ { id: 1, lang: "JavaScript", }, { id: 2, lang: "TypeScript", }, { id: 3, lang: "Python", }, ]; const App = () => { return ( <div> <ul>{languages.map((language) => ( <li key={`${language.id}_${language.lang}`}>{language.lang}</li> ))} </ul> </div> ); } ``` [了解更多](https://react.dev/learn/rendering-lists#keeping-list-items-in-order-with-key) ### 33. 如何在 Redux Thunk 中處理非同步操作? 要使用 Redux Thunk,您需要將其作為中間件導入。動作建立者不僅應該傳回一個物件,還應該傳回以調度為參數的函數。 ``` export const addUser = ({ firstName, lastName }) => { return dispatch => { dispatch(addUserStart()); } axios.post('https://jsonplaceholder.typicode.com/users', { firstName, lastName, completed: false }) .then(res => { dispatch(addUserSuccess(res.data)); }) .catch(error => { dispatch(addUserError(error.message)); }) } ``` [了解更多](https://redux.js.org/usage/writing-logic-thunks) ### 34.如何追蹤功能元件中物件欄位的變化? 為此,您需要使用“useEffect”掛鉤並將物件的欄位作為依賴項陣列傳遞。 ``` useEffect(() => { console.log('Changed!') }, [obj.someField]) ``` ### 35.如何存取DOM元素? 引用是使用 React.createRef() 或 useRef() 鉤子建立的,並透過 ref 屬性附加到 React 元素。透過存取已建立的引用,我們可以使用「ref.current」來存取 DOM 元素。 ``` const App = () => { const myRef = useRef(null); const handleClick = () => { console.log(myRef.current); // Accessing the DOM element }; return ( <div> <input type="text" ref={myRef} /> <button onClick={handleClick}>Click Me</button> </div> ); } export default App; ``` ### 36.什麼是自訂鉤子? 自訂鉤子是一個允許您在不同元件之間重複使用邏輯的功能。它是一種封裝可重複使用邏輯的方法,以便可以在多個元件之間輕鬆共用和重複使用。自訂掛鉤是通常以 **use ** 開頭的函數,並且可以根據需要呼叫其他掛鉤。 [了解更多](https://react.dev/learn/reusing-logic-with-custom-hooks) ### 37.什麼是公共API? 在索引檔案的上下文中,公共 API 通常是指向外部模組或元件公開並可存取的介面或函數。 以下是表示公共 API 的索引檔案的程式碼範例: ``` // index.js export function greet(name) { return `Hello, ${name}!`; } export function calculateSum(a, b) { return a + b; } ``` 在此範例中,index.js 檔案充當公共 API,其中導出函數“greet()”和“calculateSum()”,並且可以透過匯入它們從其他模組存取它們。其他模組可以導入並使用這些函數作為其實現的一部分: ``` // main.js import { greet, calculateSum } from './index.js'; console.log(greet('John')); // Hello, John! console.log(calculateSum(5, 3)); // 8 ``` 透過從索引檔案匯出特定函數,我們定義了模組的公共 API,允許其他模組使用這些函數。 ### 38. 建立自訂鉤子的規則是什麼? 1. 鉤子名稱以「use」開頭。 2. 如果需要,使用現有的鉤子。 3. 不要有條件地呼叫鉤子。 4. 將可重複使用邏輯提取到自訂掛鉤中。 5. 自訂hook必須是純函數。 6. 自訂鉤子可以傳回值或其他鉤子。 7. 描述性地命名自訂掛鉤。 [了解更多](https://react.dev/learn/reusing-logic-with-custom-hooks) ### 39.什麼是SSR(伺服器端渲染)? 伺服器端渲染(SSR)是一種用於在伺服器上渲染頁面並將完整渲染的頁面傳送到客戶端進行顯示的技術。它允許伺服器產生網頁的完整 HTML 標記(包括其動態內容),並將其作為對請求的回應傳送到客戶端。 在傳統的用戶端渲染方法中,用戶端接收最小的 HTML 頁面,然後向伺服器發出額外的資料和資源請求,這些資料和資源用於在客戶端渲染頁面。這可能會導致初始頁面載入時間變慢,並對搜尋引擎優化 (SEO) 產生負面影響,因為搜尋引擎爬蟲很難對 JavaScript 驅動的內容建立索引。 透過 SSR,伺服器透過執行必要的 JavaScript 程式碼來產生最終的 HTML 來負責渲染網頁。這意味著客戶端從伺服器接收完全呈現的頁面,從而減少了額外資源請求的需要。 SSR 縮短了初始頁面載入時間,並允許搜尋引擎輕鬆索引內容,從而實現更好的 SEO。 SSR 通常用於框架和函式庫中,例如用於 React 的 Next.js 和用於 Vue.js 的 Nuxt.js,以啟用伺服器端渲染功能。這些框架為您處理伺服器端渲染邏輯,讓實作 SSR 變得更加容易。 ### 40.使用SSR有什麼好處? 1. **改進初始載入時間**:SSR 允許伺服器將完全渲染的 HTML 頁面傳送到客戶端,從而減少客戶端所需的處理量。這可以縮短初始載入時間,因為使用者可以更快地看到完整的頁面。 2. **SEO友善**:搜尋引擎可以有效地抓取和索引SSR頁面的內容,因為完全渲染的HTML在初始回應中可用。這提高了搜尋引擎的可見度並有助於更好的搜尋排名。 3. **可存取性**:SSR 確保禁用 JavaScript 或使用輔助技術的使用者可以存取內容。透過在伺服器上產生 HTML,SSR 為所有使用者提供可靠且易於存取的使用者體驗。 4. **低頻寬環境下的效能**:SSR減少了客戶端需要下載的資料量,有利於低頻寬或高延遲環境下的使用者。這對於行動用戶或網路連線速度較慢的用戶尤其重要。 雖然 SSR 提供了這些優勢,但值得注意的是,與客戶端渲染方法相比,它可能會帶來更多的伺服器負載和維護複雜性。應仔細考慮快取、可擴展性和伺服器端渲染效能最佳化等因素。 ### 41.你知道Next.js的主要功能有哪些? 1. `getStaticProps`:此方法用於在建置時取得資料並將頁面預先渲染為靜態 HTML。它確保資料在建置時可用,並且不會因後續請求而更改。 ``` export async function getStaticProps() { const res = await fetch('https://api.example.com/data'); const data = await res.json(); return { props: { data } }; } ``` 2. `getServerSideProps`:此方法用於在每個請求上取得資料並在伺服器上預先渲染頁面。當您需要取得可能經常變更或特定於使用者的資料時,可以使用它。 ``` export async function getServerSideProps() { const res = await fetch('https://api.example.com/data'); const data = await res.json(); return { props: { data } }; } ``` 3. `getStaticPaths`:此方法在動態路由中使用,用於指定建置時應預先渲染的路徑清單。它通常用於獲取帶有參數的動態路由的資料。 ``` export async function getStaticPaths() { const res = await fetch('https://api.example.com/posts'); const posts = await res.json(); const paths = posts.map((post) => ({ params: { id: post.id } })); return { paths, fallback: false }; } ``` [了解更多](https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating) ### 42.什麼是 Linters? Linters 是用來檢查原始程式碼是否有潛在錯誤、錯誤、風格不一致和可維護性問題的工具。它們可幫助執行編碼標準並確保整個程式碼庫的程式碼品質和一致性。 Linters 的工作原理是掃描原始程式碼並將其與一組預先定義的規則或指南進行比較。這些規則可以包括語法和格式約定、最佳實踐、潛在錯誤和程式碼異味。當 linter 發現違反規則時,它會產生警告或錯誤,突出顯示需要注意的特定行或多行程式碼。 使用 linter 可以帶來幾個好處: 1. **程式碼品質**:Linter 有助於辨識和防止潛在的錯誤、程式碼異味和反模式,從而提高程式碼品質。 2. **一致性**:Linter 強制執行編碼約定和風格指南,確保整個程式碼庫的格式和程式碼結構一致,即使多個開發人員正在處理同一個專案時也是如此。 3. **可維護性**:透過儘早發現問題並促進良好的編碼實踐,linter 有助於程式碼的可維護性,使程式碼庫更容易理解、修改和擴展。 4. **效率**:Linter 可以透過自動化程式碼審查流程並在常見錯誤在開發或生產過程中引起問題之前捕獲它們來節省開發人員的時間。 一些流行的 linter 包括用於 JavaScript 的 ESLint 以及用於 CSS 和 Sass 的 Stylelint。 [了解更多](https://eslint.org/docs/latest/use/getting-started) ### 43.你知道哪些 React 架構解決方案? 有多種用於建立 React 專案的架構解決方案和模式。一些受歡迎的包括: 1. **MVC(模型-視圖-控制器)**:MVC 是一種傳統的架構模式,它將應用程式分為三個主要元件 - 模型、視圖和控制器。 React 可以在 View 層中使用來渲染 UI,而其他程式庫或框架可以用於 Model 和 Controller 層。 2. **Flux**:Flux是Facebook專門針對React應用程式所推出的應用架構。它遵循單向資料流,其中資料沿著單一方向流動,從而更容易理解和除錯應用程式的狀態變更。 3. **原子設計**:原子設計並不是React特有的,而是將UI分割成更小、可重複使用元件的設計方法。它鼓勵建立小型、獨立且可以組合以建立更複雜的 UI 的元件。 4. **容器和元件模式**:此模式將表示(元件)與邏輯和狀態管理(容器)分開。元件負責渲染 UI,而容器則處理業務邏輯和狀態管理。 5. **功能切片設計**:它是一種用於組織和建構 React 應用程式的現代架構方法。它旨在透過根據功能或模組劃分應用程式程式碼庫來解決可擴展性、可維護性和可重用性的挑戰。 ### 44.什麼是特徵切片設計? 它是一種用於組織和建立 React 應用程式的現代架構方法。它旨在透過根據功能或模組劃分應用程式程式碼庫來解決可擴展性、可維護性和可重用性的挑戰。 在功能切片設計中,應用程式的每個功能或模組都組織到一個單獨的目錄中,其中包含所有必要的元件、操作、reducers 和其他相關檔案。這有助於保持程式碼庫的模組化和隔離性,使其更易於開發、測試和維護。 功能切片設計促進了關注點的清晰分離,並將功能封裝在各個功能中。這允許不同的團隊或開發人員獨立地處理不同的功能,而不必擔心衝突或依賴性。 ![功能切片設計](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/amysbtftfjkuss87yu8v.png) **我強烈建議點擊“了解更多”按鈕以了解功能切片設計** [了解更多](https://dev.to/m_midas/feature-sliced-design-the-best-frontend-architecture-4noj) ## 了解更多 如果您還沒有閱讀過,我強烈建議您閱讀我關於前端面試問題的其餘文章。 https://dev.to/m_midas/52-frontend-interview-questions-javascript-59h6 https://dev.to/m_midas/41-frontend-interview-questions-css-4imc https://dev.to/m_midas/15-most-common-frontend-interview-questions-4njp ## 結論 總之,面試 React 前端開發人員職位需要對框架的核心概念、原理和相關技術有深入的了解。透過準備本文中討論的問題,您可以展示您的 React 知識並展示您建立高效且可維護的使用者介面的能力。請記住,不僅要專注於記住答案,還要理解基本概念並能夠清楚地解釋它們。 此外,請記住,面試不僅涉及技術方面,還旨在展示您解決問題的能力、溝通能力以及團隊合作能力。透過將技術專業知識與強大的整體技能相結合,您將具備在 React 前端開發人員面試中脫穎而出的能力,並在這個令人興奮且快速發展的領域找到您夢想的工作。 祝你好運!

24 款值得在 2023 年認識一下的 open source 專案

開源專案是創新、協作和創造力的遊樂場。它是來自世界各地的開發人員聚集在一起分享他們的想法、技能和熱情的中心。 在本文中,我精心挑選了 24 個涵蓋廣泛興趣和技術的開源專案。 從尖端的人工智慧框架到漂亮的生產力工具以及介於兩者之間的一切,每個開發人員都能找到適合自己的東西。 我提供了直接連結、描述和視覺效果,以便您可以立即獲得每個工具的初步印象。 原文出處:https://dev.to/madza/24-open-source-projects-for-developers-in-2023-391l --- ## 1\. [ esProc SPL](https://github.com/SPLWare/esProc)(贊助) 集算器SPL是一種基於腳本的資料操作語言,與SQL資料庫集成,支援進階分析和高效能並行處理。 它適合處理大型資料集,與各種工具集成,提供資料視覺化,並跨多個平台工作。一些主要功能包括: **💪 強大的資料處理能力:** 集算器SPL是一種腳本語言,具有豐富的函數庫和強大的語法。 **✨ 預存程序等效項:** 它允許透過 JDBC 介面執行 SPL 腳本。 **📈 多功能視覺化:** 它提供了成熟的報告工具,具有廣泛的視覺化配置,用於建立各種類型的報告。 **⚡ 自動化工作流程:** 它支援軟體工作流程的自動化,包括用於程式碼建置、測試和部署的 CI/CD 流程。 **🔥 相比SQL更具彈性:** 與SQL語法不同,集算器SPL允許將資料處理程式碼寫在多條語句中。 ![esProc_SPL](https://res.cloudinary.com/practicaldev/image/fetch/s--x_jHJEX4--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://cdn.hashnode.com/res/hashnode/image/upload/v1679824673641/82f843e0-72a1-44a4-bd99-68616f322534.png%3Fw%3D1600%26h%3D840%26fit%3Dcrop%26crop%3Dentropy%26auto%3Dcompress%2Cformat%26format%3Dwebp) ⭐ 支援他們的 GitHub 倉庫:[https://github.com/SPLWare/esProc](https://github.com/SPLWare/esProc) ## 2\. [Hoppscotch](https://github.com/hoppscotch/hoppscotch) 一種多功能開源 API 開發和測試工具,提供使用者友善的介面,用於發出 HTTP 請求來測試 API 並與 API 互動。 它簡化了製作和發送請求的過程,使其成為使用 API 的開發人員和測試人員的必備工具。 ![Hoppscotch](https://github.com/hoppscotch/hoppscotch/raw/main/packages/hoppscotch-common/public/images/banner-dark.png) ## 3\. [Supabase](https://github.com/supabase/supabase) Firebase 的開源替代方案,為開發人員提供了一組用於建立可擴展的即時應用程式的工具。 它提供了強大的後端即服務 (BaaS) 平台,具有身份驗證、資料庫管理和即時功能等功能,使其成為建立現代 Web 和行動應用程式的強大選擇。 ![Supabase](https://supabase.com/_next/image?url=%2Fimages%2Fproduct%2Fstorage%2Fheader--dark.png&w=1920&q=75) ## 4\. [Supertokens](https://github.com/supertokens/supertokens-core) 一種開源身份驗證解決方案,提供強大的安全功能和輕鬆集成,以增強 Web 和行動應用程式中的使用者身份驗證和授權。 它為開發人員提供了一個全面的工具包,用於保護用戶資料並確保無縫登入體驗。 ![Supertokens](https://supertokens.com/docs/static/assets/arch.png) ## 5\. [Git](https://github.com/git/git) Git 版本控制系統的官方開源程式庫,最初由 Linus Torvalds 建立。 Git 廣泛用於追蹤原始程式碼的更改,並透過提供強大的分支和合併功能來實現協作軟體開發。 ## 6\. [VS Code](https://github.com/microsoft/vscode) 由 Microsoft 開發的免費開源程式碼編輯器。 它提供了高度可自訂且高效的程式設計環境,具有 IntelliSense、除錯支援和龐大的擴充庫等功能,可增強您的開發工作流程。 ![VS程式碼](https://user-images.githubusercontent.com/35271042/118224532-3842c400-b438-11eb-923d-a5f66fa6785a.png) ## 7\. [OhMyZsh](https://github.com/ohmyzsh/ohmyzsh) 一個流行且高度可自訂的框架,用於在類 Unix 作業系統中管理 Zsh 配置。 它簡化了 shell 自訂,提供了大量插件和主題來增強您的命令列體驗。 ![OhMyZsh](https://cloud.githubusercontent.com/assets/2618447/6316862/70f58fb6-ba03-11e4-82c9-c083bf9a6574.png) ## 8\. [Bun](https://github.com/oven-sh/bun) 一個開源 JavaScript 工具包,旨在簡化和優化為 Web 應用程式捆綁 JavaScript 程式碼的過程。 它提供了一種現代且快速的方法來建立捆綁包,從而增強了使用 JavaScript 專案時的效能和開發人員體驗。 ![Bun](https://cdn.hashnode.com/res/hashnode/image/upload/v1696318057709/5a1125cf-eb78-4e9d-9632-faebd228abe5.png) ## 9\. [SWR](https://github.com/vercel/swr) SWR(Stale-While-Revalidate)是一個用於在 React 應用程式中取得資料的 JavaScript 函式庫。 它可以在客戶端和伺服器之間實現高效、自動的資料同步,提供無縫的即時更新,同時確保資料保持新鮮和最新。 ![SWR](https://cdn.hashnode.com/res/hashnode/image/upload/v1696318453842/d9ab3384-becc-4040-93f7-8a9e064100b1.png) ## 10\. [Prisma](https://github.com/prisma/prisma) 用於現代應用程式開發的開源資料庫工具包,透過強大的查詢產生器和類型安全的 ORM(物件關聯映射)層簡化資料庫存取和操作。 它允許開發人員使用聲明性和直觀的方法管理資料庫並與之交互,從而使資料庫操作在各種資料庫系統中無縫且安全。 ![Prisma](https://i.imgur.com/O1lwo0v.png) ## 11\. [ElasticSearch](https://github.com/elastic/elasticsearch) 由 Elastic 開發的強大且可擴展的開源搜尋和分析引擎。 它旨在幫助用戶快速有效地搜尋、分析和視覺化大量資料,使其成為從全文搜尋引擎到日誌分析等應用程式的熱門選擇。 ![ElasticSearch](https://cdn.hashnode.com/res/hashnode/image/upload/v1696315923559/58c2db03-9a6c-4b98-9b48-a91025c507a2.png) ## 12\. [Hasura](https://github.com/hasura/graphql-engine) 一款功能強大的開源工具,可簡化應用程式的 GraphQL API 開發。 借助 Hasura,您可以輕鬆建立、管理和保護 GraphQL API,從而更輕鬆地與資料來源互動並建立現代的資料驅動應用程式。 ![Hasura](https://assets.website-files.com/63e3d6905bacd6855fa38c1c/63e3d6905bacd64f08a38f95_Hasura.jpg) ## 13\. [BioDrop](https://github.com/EddieHubCommunity/BioDrop) 透過單一連結與您的受眾建立聯繫。在一處展示您建立的內容和專案。 讓人們更容易找到、關注和訂閱。 ![BioDrop](https://user-images.githubusercontent.com/624760/230707268-1f8f1487-6524-4c89-aae2-ab45f0e17f39.png) ## 14\. [Powertoys](https://github.com/microsoft/PowerToys) 適用於 Windows 的開源實用程序,可提高工作效率和自訂功能。 它提供了一系列方便的工具和實用程序,包括快速啟動器、文件預覽和視窗管理等功能,旨在簡化您的 Windows 體驗。 ![Powertoys](https://cdn.hashnode.com/res/hashnode/image/upload/v1696280333258/279d3728-4731-46eb-9836-c8300d3a9f75.png) ## 15\. [Strapi](https://github.com/strapi/strapi) 開源無頭內容管理系統 (CMS),使開發人員能夠快速建立強大且可自訂的 API。 它使團隊能夠輕鬆建立和管理內容豐富的網站和應用程式,為各種專案提供靈活性和可擴展性。 ![Strapi](https://cdn.hashnode.com/res/hashnode/image/upload/v1696316645227/6122feae-4b38-4c00-a8a1-30da5346568c.png) ## 16\. [Plausible](https://github.com/plausible/analytics) 一種開源網路分析工具,旨在為網站所有者提供對其網站效能的簡單且注重隱私的見解。 它提供用戶友好、輕量級的跟踪,且不會損害存取者的隱私,使其成為那些重視資料分析而無需侵入性跟踪方法的人的理想選擇。 ![看似](https://cdn.hashnode.com/res/hashnode/image/upload/v1696280734881/0cc0aa58-46e1-49ac-a920-65f7eaad6e33.png) ## 17\. [Astro](https://github.com/withastro/astro) 現代靜態網站產生器,透過僅傳送頁面所需的 JavaScript 來提供閃電般的效能,從而實現近乎即時的載入時間。 它將傳統伺服器渲染框架的靈活性與靜態網站產生器的速度相結合,使其成為建立高效動態網站的絕佳選擇。 ![Astro](https://deegloo.com/wp-content/uploads/2022/11/blogblog-cover-1024x614.png) ## 18\. [Remix](https://github.com/remix-run/remix) 用於建立現代 JavaScript 應用程式的 Web 框架,注重速度和開發人員體驗。 它使開發人員能夠透過無縫組合伺服器渲染和客戶端渲染的內容來建立高效能的 Web 應用程式。 ![混音](https://cdn.shopify.com/s/files/1/0779/4361/files/RemixRun_bcc7b8fd-ca3a-4385-b279-91a0606706e7.jpg?v=1666895610) ## 19\. [Tensorflow](https://github.com/tensorflow/tensorflow) 由Google開發的開源機器學習框架。 它為建立和部署機器學習模型提供了靈活且全面的生態系統,使其成為人工智慧領域研究人員和開發人員的熱門選擇。 ![Tensorflow](https://m-alcu.github.io/assets/tensorflow-playground.png) ## 20\. [Flutter](https://github.com/flutter/flutter) 由 Google 建立的開源 UI 軟體開發工具包,以其從單一程式碼庫建立適用於行動、Web 和桌面的本機編譯應用程式的能力而聞名。 它使開發人員能夠使用單一程式語言 Dart 跨多個平台建立美觀、快速且高度可自訂的使用者介面。 ![Flutter](https://cdn.hashnode.com/res/hashnode/image/upload/v1696281232879/35493958-0397-40c4-9c30-ca0faead9f39.png) ## 21\. [Kubernetes](https://github.com/kubernetes/kubernetes) 一個開源容器編排平台,可自動執行容器化應用程式的部署、擴充和管理。 它為編排容器提供了強大而靈活的基礎架構,使在雲端原生環境中大規模管理複雜的分散式系統變得更加容易。 ## 22\. [Docker](https://www.docker.com/community/open-source/) 一個開源工具,可簡化多容器 Docker 應用程式的管理。 它允許開發人員使用簡單的 YAML 檔案定義和執行多容器應用程式,從而更輕鬆地編排和部署複雜的服務。 ![Docker](https://cdn.hashnode.com/res/hashnode/image/upload/v1696316908120/7e01fe2b-a438-4882-8cd6-863b7f5effb0.png) ## 23\. [Chromium](https://github.com/chromium/chromium) Google 的一個開源瀏覽器專案,旨在為所有使用者建立更安全、更快、更穩定的網路體驗方式。 它是開發人員在網路瀏覽技術領域做出貢獻和創新的平台。 ![Chromium](https://cdn.hashnode.com/res/hashnode/image/upload/v1696319343433/61d13e7f-512b-40b7-a127-b127a944cf9d.png) ## 24\. [Linux 核心](https://github.com/torvalds/linux) 由 Linus Torvalds 和全球貢獻者社群開發的開源、類別 Unix 作業系統核心。 它作為各種基於 Linux 的作業系統的核心元件,提供硬體互動和系統管理的基本功能。 ![Linux 核心](https://upload.wikimedia.org/wikipedia/commons/2/2e/Linux_Mint_21_%22Vanessa%22_%28Cinnamon%29.png) --- 以上,簡單分享!

不是共產黨,但是審查低質量雜訊很重要!自己寫一個JS腳本過濾!

本文轉自:https://ithelp.ithome.com.tw/articles/10338948 ## 前情提要 資訊大爆炸。 有時候我們瀏覽技術文章,不一定真的是想學深奧的高級技術。 然而劣質低端的文章充斥著,則會降低我們學習的效率、甚至變成噪音與雜訊,干擾我們的思緒。 因此針對某些洗文或是質量很低的作者,我們必須列為思想犯, 否則會降低閱讀質量,平白浪費自己的時間、平台的版面、上網的電力、看到垃圾資訊的副作用等等.... ## 構思來源 如果有個思想審查警衛可以:**去除那些垃圾低端,稱不上技術文章的雜訊。** 以確保未來瀏覽文章的時候,不會再被洗文打擾, 也可以針對不喜歡的主題去封鎖,讓時間與精神更能專注於自己想要學的資訊。 阻止一些垃圾就是喜歡把自己尚未整理的白痴內容一直丟上來, 什麼都還不懂,把技術文章當成個人日記簿,寫一堆自我囈語、無病呻吟, 每天大量狂發文章,昭告天下以為這就是努力,欺騙自己也浪費別人的人生。 ## 「思想審查警衛」出動! ## 功能 1. 把頭像屏蔽 2. 加上思想通緝犯、紅字與刪除線 3. 新增封殺按鈕 4. 版面通知封殺名單與文章數 5. 透過ajax確認某id的最新ID ## 效果截圖 ![](https://i.imgur.com/kgUYJbl.png) 此截圖僅是腳本示範,跟其使用者無關, 本人沒有任何覺得此使用者發的文章是差勁的意味,我認為非常上進、值得學習。 ![](https://i.imgur.com/G27Ea2F.png) 此圖也只是隨機挑user使用,純粹作為範例用途,不代表我個人意見。 ## 腳本下載 https://greasyfork.org/zh-TW/scripts/477283-%E6%80%9D%E6%83%B3%E7%8A%AF%E5%B0%81%E6%AE%BA ## 原理說明 鄭重聲明,這個示範真的毫無任何私人意味,此腳本也只是針對不同的主題去隱藏, 例如我想學python就不想看到JS的文章,因此使用此工具幫忙隱藏罷了。 取名做思想警察、比喻成清除垃圾等都只是文學上的趣味。 請勿當真Ꮚ・ꈊ・Ꮚ 這次的技術可說比較難,認真難很多!但是趣味性以及功能性是無比的超越! 可以說幾乎是我寫系列文以來,最頂、最派的一篇! 不過很多觀念已經出現過,在【前端小試身手】系列裡面,每次的腳本都是主打實用, 因此cookie或localstorage這種技術當然都會運用到。 ## JS原始碼 ``` // ==UserScript== // @license MIT // @name 👮思想犯封殺 // @namespace http://tampermonkey.net/ // @version 0.1 // @description 把廢文製造機轟出去 // @author You // @match https://ithelp.ithome.com.tw/articles* // @match https://ithelp.ithome.com.tw/users/* // @icon https://www.google.com/s2/favicons?sz=64&domain=ithome.com.tw // @grant none // @run-at document-end // ==/UserScript== let URL = window.location.href; let ArticleSite = "https://ithelp.ithome.com.tw/articles?tab=tech" let UserSite = "https://ithelp.ithome.com.tw/users/" // 判斷URL的開頭部分 if (URL.startsWith(ArticleSite)) { //文章頁執行清理垃圾程序 CleanGarbage(); } else if (URL.startsWith(UserSite)) { UserCheck(); } else { console.log("這邊不執行腳本"); } // 餅乾儲存的機制函數------------------------------------------------- function setListInCookie(list) { document.cookie = 'myList=' + JSON.stringify(list) + '; expires=Wed, 31 Dec 2099 23:59:59 GMT;'; } // 從 Cookie 中獲取 list function getListFromCookie() { var cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)myList\s*\=\s*([^;]*).*$)|^.*$/, "$1"); return JSON.parse(cookieValue) || []; } function CleanGarbage(){ // 從本地存儲中獲取數據 var myListData = localStorage.getItem("myList"); // 解析數據到變量 list var list = myListData ? JSON.parse(myListData) : []; //list = getListFromCookie()||[]; // 儲存要刪除的字符串名單 // 找到所有CLASS是"qa-list__info-link"的<a>元素 var linkElements = document.querySelectorAll('.qa-list__info-link'); var removedCount = 0; // 初始化已清除的垃圾數量 for (var j = 0; j < list.length; j++) { // 遍歷這些<a>元素,確保文本內容包含"伍貳捌",然後刪除其父元素 for (var i = 0; i < linkElements.length; i++) { if (linkElements[i].textContent.includes(list[j])) { // 開始向上查找父元素 var parentElement = linkElements[i].parentElement; while (parentElement) { // 如果找到具有"classname"為"qa-list"的<div>元素,則刪除它 if (parentElement.classList.contains('qa-list')) { parentElement.remove(); removedCount++; // 增加清除的數量 console.warn('抓到"'+list[j]+'"這位思想犯'); break; // 找到並刪除後,結束循環 } parentElement = parentElement.parentElement; } } } if (removedCount>0){ // 顯示已清除的垃圾數量 console.log('已清除他的 ' + removedCount + ' 篇垃圾');} removedCount=0; } } //------------------------------------------------------- // 為了防止五百八改名,我們針對他的ID去ajax得到他最新的名稱 function FindBitch() { // 使用 Fetch API 獲取指定 URL 的內容 return fetch("https://ithelp.ithome.com.tw/users/20163468") .then(response => response.text()) .then(data => { // 創建一個臨時 div 元素以容納頁面內容 var tempDiv = document.createElement("div"); tempDiv.innerHTML = data; // 查找 class 為 "profile-header__name" 的元素 var profileNameElement = tempDiv.querySelector(".profile-header__name"); if (profileNameElement) { // 刪除元素內的所有 <span> 元素 var spanElements = profileNameElement.querySelectorAll("span"); spanElements.forEach(function(span) { span.remove(); }); // 讀取元素的文本內容,去掉前導和尾隨空格 var text = profileNameElement.textContent.trim(); // 返回處理後的文本內容 return text; } else { return "未找到元素"; } }) .catch(error => { console.error("發生錯誤: " + error); return "發生錯誤"; }); } //------------------------------------------------------- function UserCheck(){ //轉換資料從餅乾到localstorage var currentCookieValue = getCookie("myList"); // 2. 存儲數據到本地存儲 if (currentCookieValue) { var list = JSON.parse(currentCookieValue); // 存儲到本地存儲 localStorage.setItem("myList", JSON.stringify(list)); }else{ FindBitch() .then(text => { let FirstKill = [text]; setListInCookie(FirstKill); }) .catch(error => { console.error("找不到五百八:", error); }); } // 刪除不需要的ID document.querySelector('.profile-header__account').remove(); //封殺按鈕------------------------------------------------- // 找到具有class為"profile-header__right"的元素 var profileRightElement = document.querySelector('.profile-header__right'); var pullRightElement = profileRightElement.querySelector('.pull-right'); // 創建一個新按鈕元素 var BlockBtn = document.createElement('button'); BlockBtn.textContent = '封殺'; // 添加樣式和類名到按鈕 BlockBtn.style.marginTop = '10px'; BlockBtn.style.width = '100%'; BlockBtn.className = 'btn btn-trace trace_btn_border BlockBtn'; // 將按鈕元素添加到"pull-right"元素內部 pullRightElement.appendChild(BlockBtn); // 通緝犯名單的cookie------------------------------------------------ // 從 Cookie 中加載 list(例如,頁面加載時) list = getListFromCookie()||[]; let UserBlock = document.querySelector('.profile-header__name'); let text = UserBlock.textContent.trim(); // 如果使用者已經在封殺名單內的判斷,已存在或不存在 if (list.includes(text)) { BlockStart(BlockBtn); } else { // 針對封殺按鈕進行監聽事件 BlockBtn.addEventListener('click', function() { list.push(text); setListInCookie(list); //先加入到名單內,然後再執行封殺事件 BlockStart(); // 輸出到控制台 console.log('黑名單新增:' + text); //本地儲存機制----------------------------- let currentCookieValue = getCookie("myList"); let list2 = JSON.parse(currentCookieValue); // 存儲到本地存儲 localStorage.setItem("myList", JSON.stringify(list2)); }); } } // ------------------------------------------------ //封殺事件的函數 function BlockStart(){ let BlockBtn = document.querySelector('.BlockBtn'); BlockBtn.textContent = '已封殺'; BlockBtn.disabled = true; BadText(); BadImg(); } //封殺事件函數裡面的細項函數 function BadText(){ // 標記這傢夥是垃圾------------------------------------------------- let UserBlock = document.querySelector('.profile-header__name'); let newHeading = document.createElement('h1'); newHeading.textContent = '思想通緝犯'; // 把思想通緝犯這幾個大字加上去 UserBlock.parentElement.insertBefore(newHeading, UserBlock); UserBlock.style.textDecoration = "line-through"; UserBlock.style.color = "red"; } function BadImg(){ //圖片進行網點作業XD------------------------------------------------- var originalImage = document.querySelector('.profile-header__avatar'); // 創建一個包含交叉紅線的覆蓋層 <div> 元素 var overlayDiv = document.createElement('div'); overlayDiv.style.position = 'absolute'; overlayDiv.style.width = '150px'; overlayDiv.style.height = '150px'; overlayDiv.style.background = 'linear-gradient(45deg, black 50%, transparent 50%), linear-gradient(-45deg, black 50%, transparent 50%)'; overlayDiv.style.backgroundSize = '5px 5px, 5px 5px'; overlayDiv.style.backgroundPosition = '0 0, 0 2px'; // 將覆蓋層疊加到圖片上 originalImage.parentNode.appendChild(overlayDiv); // 設置覆蓋層的位置,以與原始圖像對齊 overlayDiv.style.top = originalImage.offsetTop + 'px'; overlayDiv.style.left = originalImage.offsetLeft + 'px'; // 設置覆蓋層的z-index,以確保它在圖片上方 overlayDiv.style.zIndex = '2'; } ``` ## 觀念筆記 這個腳本開發足足花了我一整個晚上,將近八小時之久。 有趣的是,其中為了進行測試才選某些user當作隱藏對象,否則腳本執行上會出錯。 細心的人若觀察原始碼,也會發現裡面有個firstKill, 那是必須要的段落,先設置好cookie的首要內容物,才有辦法繼續操作下去( ิ◕㉨◕ ิ) 也就是初始化的概念XD 另一個有趣的點是,為了防止使用者改名導致腳本出錯,我甚至不惜再寫一段ajax, 去更新一下ID,這樣不管人家怎麼改,都逃不了, 要改成「別抓我」也沒用,這個腳本都還是可以run。 ## 心得後記 我只能說這篇是自從「備份IT幫發文、一眼全覽」最強的JS教學文章! 超派,真的不騙( メ∀・) 有些人喜歡看前端小試身手,有些人喜歡前端動手玩創意; 其實這兩個系列的本質都是JS的教學,是可以互相連接的,但也有很多不同的重心。 這個系列就是以腳本為主,重點在於創意與發想,打到使用者痛點。 【前端動手玩創意】則是以建構網站為起點, 任何元素與概念都會變成網頁上的一部分,算是比較基礎工的建立。 如果對JS的強大感興趣,那麼可以把這兩個系列交互看,反覆的閱讀、實際動手操作, 這樣一來的學習非常踏實,甚至比YT學習都來的高效率、實際。 尤其此系列都是原創發想的腳本,當然超強! 喜歡記得關注,未來還有更多超酷的前端內容可以玩,下課⧸⎩⎠⎞͏(・∀・)⎛͏⎝⎭⧹

一位資深軟體工程師的 VSCode 設定方式&外掛套件分享

資深開發者 Jatin Sharma 在國外論壇分享了個人使用的 VSCode 設定,內容豐富,跟大家分享! 原文出處:https://dev.to/j471n/my-vs-code-setup-971 ## 🎨主題 我使用 [**Andromeda**](https://marketplace.visualstudio.com/items?itemName=EliverLara.andromeda) 作為我的 VS Code 的主要主題 ![andromeda-截圖](https://res.cloudinary.com/practicaldev/image/fetch/s--bw_aagIQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://github.com/EliverLara/Andromeda/raw/master/images/andromeda.png) ## 🪟圖標 對於圖標,我會在 [**材質圖標主題**](https://marketplace.visualstudio.com/items?itemName=PKief.material-icon-theme) 和 [**材質主題圖標**]( https://marketplace.visualstudio.com/items?itemName=Equinusocio.vsc-material-theme-icons) **找找看。** ### 材質圖標主題 ![材質圖標主題](https://i.imgur.com/xA90m2X.png) ### 材質主題圖標 ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1675233057115/b8d1623c-a092-475e-a66a-91b4a42e5441.png) ## ⚒️外掛 最讚的部分來了,有很多擴展我只提到了我最喜歡的或我每天主要使用的擴展。 ### 自動重命名標籤 自動重命名配對的 HTML/XML 標記,與 Visual Studio IDE 的操作相同。 **下載:** [**自動重命名標籤**](https://marketplace.visualstudio.com/items?itemName=formulahendry.auto-rename-tag) ![](https://github.com/formulahendry/vscode-auto-rename-tag/raw/HEAD/images/usage.gif) ### 括號對著色切換器 VS Code 擴展,為您提供一個簡單的命令來快速切換全局“括號對著色” **下載:** [**括號對著色切換器**](https://marketplace.visualstudio.com/items?itemName=dzhavat.bracket-pair-toggler) ![](https://github.com/dzhavat/bracket-pair-toggler/raw/HEAD/assets/bracket-pair-toggler-demo.gif) ### C/C++ C/C++ 擴展向 Visual Studio Code 加入了對 C/C++ 的語言支持,包括編輯 (IntelliSense) 和除錯功能。 **下載:** [**C/C++**](https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools) ![](https://i.imgur.com/0syu1Ym.png) ### 程式碼執行器 執行多種語言的程式碼片段或程式碼文件 **下載:** [**程式碼執行器**](https://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner) ![用法](https://github.com/formulahendry/vscode-code-runner/raw/HEAD/images/usage.gif) ### 程式碼拼寫檢查器 一個基本的拼寫檢查器,可以很好地處理程式碼和文件。 該拼寫檢查器的目標是幫助發現常見的拼寫錯誤,同時保持較低的誤報數量。 **下載:** [**程式碼拼寫檢查器**](https://marketplace.visualstudio.com/items?itemName=streetsidesoftware.code-spell-checker) ![示例](https://raw.githubusercontent.com/streetsidesoftware/vscode-spell-checker/main/images/example.gif) ### DotENV VSCode `.env` 語法高亮。 **下載:** [**DotENV**](https://marketplace.visualstudio.com/items?itemName=mikestead.dotenv) ![示例](https://github.com/mikestead/vscode-dotenv/raw/master/images/screenshot.png) ### 錯誤鏡頭 ErrorLens 通過使診斷更加突出來增強語言診斷功能,突出顯示語言生成的診斷的整行,並內聯打印訊息。 **下載:** [**錯誤鏡頭**](https://marketplace.visualstudio.com/items?itemName=usernamehw.errorlens) ![演示圖片](https://raw.githubusercontent.com/usernamehw/vscode-error-lens/master/img/demo.png) ### ES7+ React/Redux/React-Native 片段 ES7+ 中的 JavaScript 和 React/Redux 片段以及 [VS Code](https://code.visualstudio.com/) 的 Babel 插件功能 **下載:** [**ES7+ React/Redux/React-Native 片段**](https://marketplace.visualstudio.com/items?itemName=dsznajder.es7-react-js-snippets) ![](https://i.imgur.com/cYpm6cw.png) ### ESLint 該擴展使用安裝在打開的工作區文件夾中的 ESLint 庫。如果該文件夾未提供,則擴展程序將查找全局安裝版本。如果您尚未在本地或全局安裝 ESLint,請在工作區文件夾中執行“npm install eslint”進行本地安裝,或執行“npm install -g eslint”進行全局安裝。 **下載:** [**ESLint**](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) ![](https://i.imgur.com/R3o4517.png) ### Git 圖 查看存儲庫的 Git 圖表,並從圖表中輕鬆執行 Git 操作。可配置為您想要的外觀! **下載:** [Git Graph](https://marketplace.visualstudio.com/items?itemName=mhutchie.git-graph) ![Git Graph 記錄](https://github.com/mhutchie/vscode-git-graph/raw/master/resources/demo.gif) ### GitLens GitLens **增強了 VS Code 中的 Git,並解鎖每個存儲庫中**未開發的知識**。它可以幫助您通過 Git Blame 註釋和 CodeLens 一目了然地**可視化程式碼作者**,**無縫導航和探索** Git 存儲庫,**通過豐富的可視化和強大的比較命令**獲得有價值的見解**,等等更多的。 **下載:** [**GitLens**](https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens) ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1675224552887/688896dd-cfff-41fc-aa2e-53716e5585c6.png) ### HTML 樣板 此擴展提供了所有 Web 應用程式中使用的標準 HTML 樣板程式碼。 **下載:** [**HTML 樣板**](https://marketplace.visualstudio.com/items?itemName=sidthesloth.html5-boilerplate) ![替代文本](https://s19.postimg.cc/3mig98d5v/html_boilerplate_1_0_3.gif) ### Import Cost 此擴展將在編輯器中內聯顯示導入包的大小。該擴展利用 webpack 來檢測導入的大小。 **下載:** [**Import Cost**](https://marketplace.visualstudio.com/items?itemName=wix.vscode-import-cost) ![示例圖片](https://citw.dev/_next/image?url=%2fposts%2fimport-cost%2f1quov3TFpgG2ur7myCLGtsA.gif&w=1080&q=75) ### Live Server 它將啟用實時更改而不保存文件。 **下載:** [**Live Server**](https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer) ![實時伺服器演示 VSCode](https://github.com/ritwickdey/vscode-live-server/raw/HEAD/images/Screenshot/vscode-live-server-animated-demo.gif) ### Markdown 多合一 Markdown 所需的一切(鍵盤快捷鍵、目錄、自動預覽等)。 ***注意***:VS Code 具有開箱即用的基本 Markdown 支持(例如,**Markdown 預覽**),請參閱官方文件了解更多訊息。 **下載:** [**Markdown All in One**](https://marketplace.visualstudio.com/items?itemName=yzhang.markdown-all-in-one) ![切換粗體gif](https://github.com/yzhang-gh/vscode-markdown/raw/master/images/gifs/toggle-bold.gif) ### Markdown 預覽增強 它顯示了 Markdown 內容的增強預覽。 **下載:** [**Markdown 預覽增強版**](https://marketplace.visualstudio.com/items?itemName=shd101wyy.markdown-preview-enhanced) ![簡介](https://user-images.githubusercontent.com/1908863/28495106-30b3b15e-6f09-11e7-8eb6-ca4ca001ab15.png) ### 將 JSON 粘貼為程式碼 複製 JSON,粘貼為 Go、TypeScript、C#、C++ 等。 **下載 -** [**將 JSON 粘貼為程式碼**](https://marketplace.visualstudio.com/items?itemName=quicktype.quicktype) ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/llqdlpz0amo1vj7m5no5.png) ### 更漂亮 使用 Prettier 的程式碼格式化程序 **下載 -** [**Prettier**](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) ![更漂亮](https://i.imgur.com/wHlMe9e.png) ### Python IntelliSense (Pylance)、Linting、除錯(多線程、遠程)、Jupyter Notebooks、程式碼格式化、重構、單元測試等。 **下載 -** [**Python**](https://marketplace.visualstudio.com/items?itemName=ms-python.python) ![Python](https://i.imgur.com/cQ1ARrG.png) ### 設置同步 使用 GitHub Gist 跨多台計算機同步設置、程式碼片段、主題、文件圖標、啟動、按鍵綁定、工作區和擴展。 **下載 -** [**設置同步**](https://marketplace.visualstudio.com/items?itemName=Shan.code-settings-sync) ![設置同步](https://shanalikhan.github.io/img/login-with-github.png) ### Tailwind CSS IntelliSense 適用於 VS Code 的智能 Tailwind CSS 工具 **下載 -** [**Tailwind CSS IntelliSense**](https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss) ![Tailwind CSS IntelliSense](https://raw.githubusercontent.com/bradlc/vscode-tailwindcss/master/packages/vscode-tailwindcss/.github/banner.png) ### 所有亮點 突出顯示程式碼中的“TODO”、“FIXME”和其他註釋。 有時,在將程式碼發佈到生產環境之前,您會忘記檢查編碼時加入的 TODO。所以我長期以來一直想要一個擴展來突出顯示它們並提醒我還有註釋或尚未完成的事情。 希望這個擴展也能幫助您。 **下載 -** [**TODO 突出顯示**](https://marketplace.visualstudio.com/items?itemName=wayou.vscode-todo-highlight) ![TODO 突出顯示](https://github.com/wayou/vscode-todo-highlight/raw/master/assets/material-night.png) ### Turbo 控制台日誌 自動編寫有意義的日誌訊息的過程。 **下載 -** [**Turbo 控制台日誌**](https://marketplace.visualstudio.com/items?itemName=ChakrounAnas.turbo-console-log) ![Turbo 控制台日誌](https://image.ibb.co/dysw7p/insert_log_message.gif) ### 塔布寧人工智能 Tabnine 是一款 AI 程式碼助手,可讓您成為更好的開發人員。 Tabnine 將通過所有最流行的編碼語言和 IDE 中的實時程式碼完成來提高您的開發速度。 **下載 -** [**Tabnine AI**](https://marketplace.visualstudio.com/items?itemName=TabNine.tabnine-vscode) ![Tabnine AI](https://raw.githubusercontent.com/codota/tabnine-vscode/master/assets/completions-main.gif) ## ⚙️設置 以下“JSON”程式碼顯示了我的 VS Code 設置: ``` // user/settings.json { "files.autoSave": "afterDelay", "editor.mouseWheelZoom": true, "code-runner.clearPreviousOutput": true, "code-runner.ignoreSelection": true, "code-runner.runInTerminal": true, "code-runner.saveAllFilesBeforeRun": true, "code-runner.saveFileBeforeRun": true, "editor.wordWrap": "on", "C_Cpp.updateChannel": "Insiders", "editor.suggestSelection": "first", "python.jediEnabled": false, "editor.fontSize": 17, "emmet.includeLanguages": { "javascript": "javascriptreact" }, "editor.minimap.size": "fit", "editor.fontFamily": "Consolas, DejaVu Sans Mono, monospace", "editor.fontLigatures": false, "[html]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "python.formatting.provider": "yapf", "[css]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "git.autofetch": true, "git.enableSmartCommit": true, "html-css-class-completion.enableEmmetSupport": true, "editor.formatOnPaste": true, "liveServer.settings.donotShowInfoMsg": true, "[python]": { "editor.defaultFormatter": "ms-python.python" }, "diffEditor.ignoreTrimWhitespace": false, "[json]": { "editor.defaultFormatter": "vscode.json-language-features" }, "[c]": { "editor.defaultFormatter": "ms-vscode.cpptools" }, "editor.fontWeight": "300", "editor.fastScrollSensitivity": 6, "explorer.confirmDragAndDrop": false, "vsicons.dontShowNewVersionMessage": true, "workbench.iconTheme": "material-icon-theme", "editor.defaultFormatter": "esbenp.prettier-vscode", "editor.renderWhitespace": "none", "workbench.startupEditor": "newUntitledFile", "liveServer.settings.multiRootWorkspaceName": "", "liveServer.settings.port": 5000, "liveServer.settings.donotVerifyTags": true, "editor.formatOnSave": true, "html.format.indentInnerHtml": true, "editor.formatOnType": true, "printcode.tabSize": 4, "terminal.integrated.confirmOnExit": "hasChildProcesses", "terminal.integrated.cursorBlinking": true, "terminal.integrated.rightClickBehavior": "default", "tailwindCSS.emmetCompletions": true, "sync.gist": "527c3e29660c53c3f17c32260188d66d", "gitlens.hovers.currentLine.over": "line", "terminal.integrated.profiles.windows": { "PowerShell": { "source": "PowerShell", "icon": "terminal-powershell" }, "Command Prompt": { "path": [ "${env:windir}\\Sysnative\\cmd.exe", "${env:windir}\\System32\\cmd.exe" ], "args": [], "icon": "terminal-cmd" }, "Git Bash": { "source": "Git Bash" }, "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe (migrated)": { "path": "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", "args": [] }, "Windows PowerShell": { "path": "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" }, "Ubuntu (WSL)": { "path": "C:\\WINDOWS\\System32\\wsl.exe", "args": [ "-d", "Ubuntu" ] } }, "javascript.updateImportsOnFileMove.enabled": "always", "[dotenv]": { "editor.defaultFormatter": "foxundermoon.shell-format" }, "editor.tabSize": 2, "cSpell.customDictionaries": { "custom-dictionary-user": { "name": "custom-dictionary-user", "path": "~/.cspell/custom-dictionary-user.txt", "addWords": true, "scope": "user" } }, "window.restoreFullscreen": true, "tabnine.experimentalAutoImports": true, "files.defaultLanguage": "${activeEditorLanguage}", "bracket-pair-colorizer-2.depreciation-notice": false, "workbench.editor.wrapTabs": true, "[markdown]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[ignore]": { "editor.defaultFormatter": "foxundermoon.shell-format" }, "terminal.integrated.fontFamily": "courier new", "terminal.integrated.defaultProfile.windows": "pwsh.exe -nologo", "terminal.integrated.shellIntegration.enabled": true, "terminal.integrated.shellIntegration.showWelcome": false, "editor.accessibilitySupport": "off", "editor.bracketPairColorization.enabled": true, "todohighlight.isEnable": true, "terminal.integrated.shellIntegration.history": 1000, "turboConsoleLog.insertEnclosingClass": false, "turboConsoleLog.insertEnclosingFunction": false, "files.autoSaveDelay": 500, "liveServer.settings.CustomBrowser": "chrome", "liveServer.settings.host": "localhost", "liveServer.settings.fullReload": true, "workbench.editor.enablePreview": false, "workbench.colorTheme": "Andromeda Bordered" } ``` ## 總結 以上簡單分享,希望對您有幫助!

改善重用性: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

分享職場小菜雞所遇到的狀況

感謝站長關懷~ 是的,這禮拜確實有遇到一些之前有稍微碰過卻不太熟悉的東西,也有之前沒有碰過的東西,是有些小崩潰...,但還是可以稍微跟大家分享與請教一下: 這裡有一些前期提要:公司目前的前端開發並不使用現在的主流前端框架,也沒有使用打包整合工具...(像是Webpack、Parcel這類的),JS使用JQuery,並且將JS檔案一個一個的引入網頁中。 ## 遇到的問題1 :CSS樣式問題 過去在自學的時候其開發方法是:在本機開發,然後在處理樣式與RWD時就是開啟Chrome 的 Dev Tools來做調整,但也有遇過在Chrome的Dev Tools中看起來將樣式都調整好了之後,部署到網路上之後換手機來查看頁面時卻發生了一些差異,這些差異可能包含滿版、間距等等,這部分我自己理解的差異可能會是有些手機會有瀏海的緣故以及Chrome與Safari之間的小差異.到新公司後發現在更多的裝置上,例如安卓手機,則存在的差異更多,包含顏色、日期時間選取器等等的樣式,因為型號真的太多了. ###到這裡可以跟大家分享的以及向各位請教的: 這裡我自己有想到幾個解決的方式,第一個是最懶的方法我最想用但是我有些不知道該如何整合給其他人使用的方法,例如透過Vue cli直接在npm下載PostCSS以及Autoprefixer這樣的工具來使用,一次解決主流瀏覽器的差異,但目前我不太曉得如何在公司的開發方法下,不透過整合工具來完成這個流程. 另一個我想到的方法是加入CSS Normalize來減少各個瀏覽器在不同樣式的預設值差異,過去我們可能都有寫過非常簡易CSS reset 例如: ```css= *{ padding: 0; margin:0; box-sizing:border-box; } ``` 但這樣如果把每一個樣式的預設值全部強制歸零,可能會導致有些樣式到後來要重新寫,或許Normalize可以只是單純地減少差異(也是因為網路上有人已經整理好了XD). ## 遇到的問題2 :API串接 過去我自己練習串接API的方式實在是相當簡易,我拿的是中央氣象局開放資料平台的API,所以之前很簡單的一行fetch就拿到資料了,毫無難度哈哈哈,但第一天公司需要我去切幾個版面並且串接運輸資料TDX的資料,恩...我一開始不知道要如何在JS中塞入登入資料並且拿回Token的方式.以及我要查詢的數值該如何發出. ###到這裡可以跟大家分享的以及向各位請教的: 這中間我摸索了fetch的一些選項設定,這應該也適用其他的非同步請求方法,例如ajax、axios(這兩個我還沒用過,後續應該會來摸索一下axios),包含請求方法(method),header與body中的內容設定等等. 至於API該如何塞入a頁面填入查詢參數並且跳轉到b頁面顯示查詢解果,在沒有前端框架全域狀態管理的支援下,這邊則是摸索了encodeURIComponent以及decodeURIComponent這樣的函式,將要查詢的參數在a頁面進行編碼並丟入到URL中,跳轉到b頁面後再進行解碼.並fetch我要的資料.最後是有成功的,只是覺得自己像薪水小偷哈哈哈,效率並不高. 這個方法感覺並不建議應用在需要輸入有個人資料的內容中,因為編碼的方式是雙向的,資料可以編碼也可以解碼,所以....像個資這類的內容就應該不建議塞在URL中用這種方式傳輸.至於要用什麼方法,這也是我想知道的. ## 遇到的問題3:不同裝置的問題 這個並非第一個樣式的問題,而是我目前覺得還沒有解的問題,就是我在網頁中需要獲取使用者的位置,因此用了navigator.geolocation 這個API,但神奇的是,在本機中都可以抓得到資料,打開Dev Tools檢查回傳的狀態碼與經緯度也都是沒有問題,但是在手機中雖然會顯示是否能夠取得使用者位置的提示,但按了同意後卻一直無法獲取資料,而且尷尬的是,我無法在手機中打開Dev Tools,所以我也不知道問題發生在哪....,過去有使用過navigator.geolocation 好像也沒有碰過這樣的問題 想跟各位請教的是,有什麼方式可以查看手機上的問題嗎? ## 遇到的問題4:不同的開發方式 這個是我自己很好奇的,雖然說我知道Vue是漸進式框架,但我卻不知道該如何漸進.我理解的漸進式是,有些頁面或元件可以自行選擇要不要使用Vue開發,還是這個漸進式的意思是可以自行選擇要使用多少Vue的套件工具呢(像是要不要使用Vue Router or Vuex). 會這樣問是因爲,假如現在有一份專案一共是十個頁面,我被分到了其中五頁,另外的同事則是負責另外五頁,誠如開頭所說,假如公司既定的開發方式並不使用框架與其他整合工具,我有可能使用框架進行開發並與之合作嗎?還是我這是一個很奇怪的問題,本來就應該要統一一個開發方式? --- 感謝看到這邊的各位,以上有些觀念上是我這位小菜雞自己摸索的,是可能不是正確的(例如有些函式、工具的用途或使用情境),因此歡迎大家指教與討論,這是我這禮拜可以跟大家分享的啦. 謝謝~~ --- PS:我自學八個月的時間有摸了原生JS、CSS、Vue.js、Tailwind、SCSS這樣的工具,本來我是很想要在第一份工作多了解與強化上述工具以及多人開發GitHub的部分,我了解這些終究只是工具且我自己也沒有到非常熟,只要可以完成專案目的即可,我的實力在哪裡我也知道,但以目前公司的開發模式來說,我需要考量沒有踏上趨勢的這個問題嗎?還是我多慮呢了?

Git 入門上手教材:第7課 ── 學會處理 git 衝突

## 課程目標 - 學會處理 git 衝突 ## 課程內容 這課來學一下 commit 彼此有衝突,而 git 沒辦法自動合併的情況吧 先挑一個資料夾,把 `my-work-1.html` 裡面隨意加上幾行內容 ``` <p>我的第一個網頁檔案</p> <p>new content a</p> <p>new content b</p> <p>new content c</p> ``` 接著 ``` git add my-work-1.html git commit -m 'new content abc' git push ``` 順利送出! 然後去另一個資料夾,把 `my-work-1.html` 裡面隨意加上幾行內容 ``` <p>我的第一個網頁檔案</p> <p>new content x</p> <p>new content y</p> <p>new content z</p> ``` 接著 ``` git add my-work-1.html git commit -m 'new content xyz' git push ``` 結果失敗了!一如預期,被 git 喊停了 ``` To github.com:howtomakeaturn/my-first-testing-repo.git ! [rejected] main -> main (fetch first) error: failed to push some refs to 'github.com:howtomakeaturn/my-first-testing-repo.git' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes hint: (e.g., 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. ``` 預期之中,這時應該 pull 對吧? ``` git pull ``` ``` remote: Enumerating objects: 14, done. remote: Counting objects: 100% (12/12), done. remote: Compressing objects: 100% (4/4), done. remote: Total 8 (delta 3), reused 8 (delta 3), pack-reused 0 Unpacking objects: 100% (8/8), 792 bytes | 79.00 KiB/s, done. From github.com:howtomakeaturn/my-first-testing-repo d999c25..2cf01f4 main -> origin/main hint: Pulling without specifying how to reconcile divergent branches is hint: discouraged. You can squelch this message by running one of the following hint: commands sometime before your next pull: hint: hint: git config pull.rebase false # merge (the default strategy) hint: git config pull.rebase true # rebase hint: git config pull.ff only # fast-forward only hint: hint: You can replace "git config" with "git config --global" to set a default hint: preference for all repositories. You can also pass --rebase, --no-rebase, hint: or --ff-only on the command line to override the configured default per hint: invocation. Auto-merging my-work-1.html CONFLICT (content): Merge conflict in my-work-1.html Automatic merge failed; fix conflicts and then commit the result. ``` 在前一課,我們 pull 之後,會被 git 自動把雲端版本、跟本機你剛改過的版本,合併在一起,然後在終端機編輯器內,請你打一段小訊息,備註這次合併 這次,卻沒有進入終端機編輯器內,而是跳出一串訊息! 注意看最後幾行! ``` Auto-merging my-work-1.html CONFLICT (content): Merge conflict in my-work-1.html Automatic merge failed; fix conflicts and then commit the result. ``` 這就是 commit 衝突的情況:兩個 commit 都有改到同樣檔案,雖然先後時間不同,但是 git 不敢直接用新的蓋掉舊的! git status 看一下 ``` Unmerged paths: (use "git add <file>..." to mark resolution) both modified: my-work-1.html ``` 清楚寫出了:both modified,兩邊都修改過! 打開 `my-work-1.html` 看一下 ``` <p>我的第一個網頁檔案</p> <<<<<<< HEAD <p>new content x</p> <p>new content y</p> <p>new content z</p> ======= <p>new content a</p> <p>new content b</p> <p>new content c</p> >>>>>>> 2cf01f4f63f5ea9040610495688f08032761a170 ``` 看起來很嚇人,其實,只是 git 怕你看不清楚,用一種誇飾法,列出衝突的地方而已! HEAD 段落,是你剛提交的 commit 部份 `2cf01f4f63f5ea9040610495688f08032761a170` 的部份呢?則是剛剛從 github 抓下來的 commit 代號! 要如何處理衝突呢?其實,你就決定一下,衝突這幾行,到底要怎麼合併就可以了,然後把 git 誇飾法的地方刪掉 比方說,我決定讓行數交錯呈現吧 ``` <p>我的第一個網頁檔案</p> <p>new content a</p> <p>new content x</p> <p>new content b</p> <p>new content y</p> <p>new content c</p> <p>new content z</p> ``` 改完之後 ``` git add my-work-1.html ``` ``` git commit -m 'handle conflict' ``` 手動合併的 commit,我個人通常習慣訊息就寫 handle conflict ``` git push ``` 大功告成!這就是所謂的 git 衝突處理 ## 課後作業 接續前一課的作業 在上一次的作業,我們嘗試了兩個資料夾,同時 push 送出 commit,導致 git 比對 github 上的雲端版本時,發現有衝突,請你先 pull 再 push 的情況 上次的情況比較單純,因為雖然有衝突,但是 git 一看就知道影響不大,所以 pull 時自動處理了衝突,把事情都安排好了 這次的作業,我們要模擬「遇到衝突,而且 git 無法自動處理衝突」的情況 --- 請按照以下步驟,送出 commit **第一步** 到 `at-home` 資料夾,打開檔案 `about.html` 的內容,原本是 ``` <h1>我是誰</h1> <p>我是XXX,目前在自學網頁開發</p> ``` 請改成 ``` <h1>我是誰</h1> <p>我是XXX,目前在自學網頁開發,目標是成為厲害的前端工程師</p> ``` 然後送出 commit,接著 `git push` 出去 你會看到 github 上面就被更新了 **第二步** 到 `at-laptop` 資料夾,假設你今天出門工作,忘記先 pull 了,也忘記檔案其實你已經改好了 打開檔案 `about.html` 的內容,依然是 ``` <h1>我是誰</h1> <p>我是XXX,目前在自學網頁開發</p> ``` 請改成 ``` <h1>我是誰</h1> <p>我是XXX,目前在自學網頁開發,目標是成為厲害的軟體工程師</p> ``` 然後送出 commit,接著 `git push` 出去 這時 git 會請你先更新,於是你輸入 `git pull` 你會發現 git 表示遇到衝突,無法自動合併,請你處理! 原來有一邊是寫「前端工程師」,另一邊是寫「軟體工程師」 git 無法自動判斷你到底是想要以哪個為準!(其實用哪個都可以吧!) 請處理這個 conflict 衝突,處理完之後 push 到 github 上面 完成以上任務,你就完成這次的課程目標了! --- 交作業的方法: 可以把 github 專案連結,貼到留言區

Git 入門上手教材:第6課 ── 學會 git pull

## 課程目標 - 學會 git pull ## 課程內容 學會把專案上傳 github 了,這次來試試把專案從 github 載下來吧 假設你現在使用另一台新電腦,專案還不在你的電腦上 打開專案頁面 https://github.com/howtomakeaturn/my-first-testing-repo 頁面上有一個 `Code` 的按鈕,點下去有 clone(複製)的指示 在電腦上先移動到別的資料夾底下,使用 clone 指令把專案抓下來 ``` git clone [email protected]:howtomakeaturn/my-first-testing-repo.git ``` 完成之後,會看到在新資料夾底下,有一份一模一樣的專案! --- 在新資料夾底下,把 `my-work-3.html` 裡面隨意加上幾個字,接著 ``` git add my-work-3.html git commit -m 'commit from new folder' git push ``` 打開 github,會在上面看到有被更新! --- 回到之前的「舊資料夾」底下,把 `my-work-4.html` 裡面隨意加上幾個字,接著 ``` git add my-work-4.html git commit -m 'commit from old folder' git push ``` 會發現上傳失敗! ``` To github.com:howtomakeaturn/my-first-testing-repo.git ! [rejected] main -> main (fetch first) error: failed to push some refs to 'github.com:howtomakeaturn/my-first-testing-repo.git' hint: Updates were rejected because the remote contains work that you do hint: not have locally. This is usually caused by another repository pushing hint: to the same ref. You may want to first integrate the remote changes hint: (e.g., 'git pull ...') before pushing again. hint: See the 'Note about fast-forwards' in 'git push --help' for details. ``` 原因是,git 發現,你從兩個不同的地方,分別更新過不同檔案,git 怕你會搞混編輯歷史紀錄 (github 上現在有4筆 commit,目前資料夾上也是4筆 commit,git 無法分辨哪個第4筆是最新的) 所以 git 希望你能先把最新版本抓下來,再送出你的版本,比較不會有爭議! 把新版本抓下來的指令是 ``` git pull ``` 抓完之後,因為 git 自動把雲端版本、跟本機你剛改過的版本,合併在一起了 會請你打一段小訊息,備註這次合併 通常你就使用 `ctrl + x` 或者 `:q` 離開終端機編輯器就可以了 完成之後,使用 `git log` 會看到,現在有6筆 commit 紀錄,最後一筆是剛剛自動合併的 commit ``` Merge branch 'main' of github.com:howtomakeaturn/my-first-testing-repo ``` 使用 `git status` 也會看到 ``` On branch main Your branch is ahead of 'origin/main' by 2 commits. (use "git push" to publish your local commits) nothing to commit, working tree clean ``` git 提示你目前比雲端版本還多了 2 筆 commit(一筆是你剛加的,一筆是關於自動合併的) 使用 `git push` 通通推上去 github 吧! --- 看到這邊你可能會想,剛剛那筆自動合併的 commit 好像有點多餘? 就把 `commit from new folder` 以及 `commit from old folder` 按照時間順序排列,不就好了嗎? 其實,那是因為這兩筆 commit 內容沒有重疊,所以看起來很單純 實務上很多時候,兩筆 commit 會更新到「相同的檔案」之中的「同樣幾行程式碼」 這時 git 如果按照時間順序排列,就會讓「較晚送出 commit 的人」把「較早送出 commit 的人」的工作內容覆蓋掉! 這樣一來,根本沒辦法團隊工作:晚提交的人,會一直破壞掉早提交的內容! 所以 git 一律會多一筆「合併 commit」。平常就自動合併沒問題,有衝突時,就可以在這筆 commit 處理 有點不懂沒關係,我們下一課會練習 ## 課後作業 接續前一課的作業,專案已經傳到 github 了 假設你原本是用家裡的電腦開發,現在你打算帶著筆電,出門到咖啡廳繼續開發 請拿出你的筆電,把 github 上那個專案 `git clone` 到筆電上面 如果你沒有筆電,沒關係,在電腦上另外找個資料夾,用 `git clone` 從 github 抓專案下來 這樣兩個資料夾對應同一個專案,也可以,模擬跨裝置同步專案 --- 現在分別有兩個資料夾,內容一模一樣,我這邊分別用 `at-home` 以及 `at-laptop` 稱呼兩個資料夾 請按照以下步驟,送出 commit **第一步** 到 `at-home` 資料夾,建立一個檔案 `create-this-file-at-home.html` 內容放 ``` <p>我在家裡新增這個檔案</p> ``` 然後送出 commit,接著 `git push` 出去 你會看到 github 上面就被更新了 **第二步** 到 `at-laptop` 資料夾,建立一個檔案 `create-this-file-at-laptop.html` 內容放 ``` <p>我在咖啡廳新增這個檔案</p> ``` 然後送出 commit,接著 `git push` 出去 你會看到錯誤訊息! git 會跟你說,有衝突,請先將資料夾內容下載同步,再更新 **第三步** 所以請輸入 `git pull` 先把資料夾更新到最新版本 接著用 `git log` 看一下,會看到有關 `create-this-file-at-home.html` 那個檔案的 commit **第四步** 這時再 `git push` 出去 你會看到 github 上面就被更新了 完成以上任務,你就完成這次的課程目標了! --- 交作業的方法: 可以把 github 專案連結,貼到留言區

寫了多年 React 之後,改寫 Svelte 的心得與感想

原文出處:https://dev.to/mikenikles/why-i-moved-from-react-to-svelte-and-others-will-follow-210l # React 多年來一直是我的首選 2015 年 10 月 14 日,我主持了 [首屆 React 溫哥華聚會](https://www.meetup.com/ReactJS-Vancouver-Meetup/events/225362860/)。當時我在一年中的大部分時間裡都在使用 React,並希望將志同道合的開發人員聚集在一起。 那時的 React,我敢說,是 web 前端世界的革命性的。與 jQuery、Backbone.js 或 Angular 1.x 等替代方案相比,使用 React 進行開發感覺直觀、清新且富有成效。就個人而言,隔離建置塊(又名元件)的想法真的很吸引我,因為它自然會導致結構化、組織良好且更易於維護的程式碼庫。 在接下來的幾年裡,我一直密切關注 Angular 2.x+、Vue 等,但沒有一個是值得跳槽的選擇。 # 然後我了解了 Svelte 我第一次了解 Svelte 是在 2018 年年中,也就是 3.0 版發布前將近一年(見下文)。 “[計算機,為我建置一個應用程式。](https://www.youtube.com/watch?v=qqt6YxAZoOc)”[Rich Harris](https://twitter.com/Rich_Harris) 讓我著迷Svelte。 > 如果您不熟悉 Svelte ([https://svelte.dev/](https://svelte.dev/)),請存取網站並花 5 分鐘閱讀介紹。 閱讀了嗎?真的?優秀👍 看完影片後,我心中的主要問題是是否值得學習 Svelte 並開始將其用於新專案甚至現有專案。平心而論,Svelte 給我留下了深刻的印象,但仍然不足以讓我完全接受它。 # Svelte 3.x 2019 年 4 月 22 日 - [Svelte 3:重新思考反應性](https://svelte.dev/blog/svelte-3-rethinking-reactivity) 是我一直在等待的博文。 > 請花一些時間閱讀博文並[觀看影片](https://www.youtube.com/watch?v=AdNJ3fydeao) - 這是關於電子表格的,但我保證它很有趣😉 為什麼這是一件大事?首先,Svelte 團隊一直在談論版本 3,我想看看它的實際應用。另一方面,Svelte 及其承諾比我第一次聽說 React 時更讓我興奮。 那時我指導 Web 開發人員,並花了很多時間讓他們加快 React 的速度。為了開發 React 應用程式,需要學習、理解並在一定程度上掌握 JSX、CSS-in-JS、Redux、create-react-app、SSR 和其他概念。 > 對於 Svelte,這些都不是必需的。 ``` <script> let name = 'world'; </script> <style> h1 { color: blue; } </style> <h1>Hello {name}!</h1> ``` 夠簡單嗎?我同意。事實上,它非常簡單,我將它推薦給我的 Web 開發新手。 ## 很快,那段程式碼發生了什麼? `script` 標籤是元件邏輯所在的位置。 `style` 標籤定義了這個元件的 CSS - 這些都不會洩漏到元件之外,所以我們可以安全地使用 h1 並且它只適用於這個元件。它是真正的 CSS,而不是偽裝成 CSS 的 Javascript 對像或偽裝成 CSS 的字串文字。 底部是元件的 HTML。使用帶有 `{myVariable}` 的變數。與 React 的 JSX 相比,Svelte 允許您使用正確的 HTML 標籤,例如 `for`、`class` 而不是 `forHtml` 和 `className`。請參閱 React 文件中的“[屬性差異](https://reactjs.org/docs/dom-elements.html#differences-in-attributes)”以獲取所有非標準 HTML 屬性的列表。 # 讓我們重建 React 示例 為了讓您了解 Svelte 與 React 的對比,讓我們重新建置 [https://reactjs.org/](https://reactjs.org/) 上列出的內容。 ## 一個簡單的元件 請參閱上面的程式碼片段。 ## 一個有狀態的元件 [互動演示](https://svelte.dev/repl/6e9ef214ae774287b21f902d7e6f0e68?version=3.16.6) ``` <script> let seconds = 0; setInterval(() => seconds += 1, 1000); </script> Seconds: {seconds} ``` React:33行 Svelte:6 行 ## 一個應用程式 [互動演示](https://svelte.dev/repl/817d413fd6c344bf859f0dbf8063de2f?version=3.16.6) ``` <script> /* App.svelte */ import TodoList from './TodoList.svelte'; let items = []; let text = ''; const handleSubmit = () => { if (!text.length) { return } const newItem = { text, id: Date.now(), }; items = items.concat(newItem); } </script> <div> <h3>TODO</h3> <TodoList {items} /> <form on:submit|preventDefault={handleSubmit}> <label for="new-todo"> What needs to be done? </label> <input id="new-todo" bind:value={text} /> <button> Add #{items.length + 1} </button> </form> </div> ``` ``` <script> /* TodoList.svelte */ export let items = []; </script> <ul> {#each items as item} <li key={item.id}>{item.text}</li> {/each} </ul> ``` React:66行 Svelte:43 行 ## 使用外部插件的元件 [互動演示](https://svelte.dev/repl/28f4b2e36e4244b8b23cae3d584c4c88?version=3.16.6) ``` <script> const md = new window.remarkable.Remarkable(); let value = 'Hello, **world**!'; </script> <svelte:head> <script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/2.0.0/remarkable.min.js"></script> </svelte:head> <div className="MarkdownEditor"> <h3>Input</h3> <label htmlFor="markdown-content"> Enter some markdown </label> <textarea id="markdown-content" bind:value={value} /> <h3>Output</h3> <div className="content"> {@html md.render(value)} </div> </div> ``` React:42行 Svelte:24 行 > 更少的程式碼 = 更少的錯誤 > 更少的程式碼 = 更好的性能 = 更好的用戶體驗 > 更少的程式碼 = 更少的維護 = 更多的時間來開發功能 # 我還喜歡 Svelte 什麼? ## 反應性 另一個強大的功能是 [反應式聲明](https://svelte.dev/tutorial/reactive-declarations)。讓我們從一個例子開始: ``` <script> let count = 0; $: doubled = count * 2; function handleClick() { count += 1; } </script> <button on:click={handleClick}> Clicked {count} {count === 1 ? 'time' : 'times'} </button> <p>{count} doubled is {doubled}</p> ``` 每當你有依賴於其他變數的變數時,用 `$: myVariable = [引用其他變數的程式碼]` 聲明它們。以上,每當 count 發生變化時,doubled 都會自動重新計算,並且 UI 會更新以反映新值。 ## Stores 在需要跨元件共享狀態的情況下,Svelte 提供了存儲的概念。 [教程很好地解釋了 store](https://svelte.dev/tutorial/auto-subscriptions)。無需閱讀冗長的教程 - store 就這麼簡單。 ### Derived stores 通常,一家 store 依賴於其他 store。這就是 Svelte 提供 derived() 來組合 store 的地方。 [有關詳細訊息,請參閱教程](https://svelte.dev/tutorial/derived-stores)。 ## 作為邏輯塊等待 好吧,這是一個非常優雅的。讓我們從程式碼開始([交互式演示](https://svelte.dev/repl/b9fc662a253443dc901ff189ce1cdd4b?version=3.16.7)): ``` <script> let githubRepoInfoPromise; let repoName = 'mikenikles/ghost-v3-google-cloud-storage'; const loadRepoInfo = async () => { const response = await fetch(`https://api.github.com/repos/${repoName}`); if (response.status === 200) { return await response.json(); } else { throw new Error(response.statusText); } } const handleClick = () => { githubRepoInfoPromise = loadRepoInfo(); } </script> <input type="text" placeholder="user/repo" bind:value={repoName} /> <button on:click={handleClick}> load Github repo info </button> {#await githubRepoInfoPromise} <p>...loading</p> {:then apiResponse} <p>{apiResponse ? `${apiResponse.full_name} is written in ${apiResponse.language}` : ''}</p> {:catch error} <p style="color: red">{error.message}</p> {/await} ``` 看到 HTML 中的“#await”塊了嗎?在真實世界的應用程式中,您將有一個加載元件、一個錯誤元件和在這種情況下呈現 API 響應的實際元件。嘗試在文本框中輸入無效的 repo 名稱以觸發錯誤案例。 # “等等,那……呢?” ## 開源元件? 當我向某人介紹 Svelte 時,我得到的主要回應是“但是生態系統、元件、教程、工具等呢?” 是的,開源 Svelte 元件遠不及 React 元件多。話雖如此,您多久使用一個開源 React 元件並在沒有任何問題或不必要的開銷的情況下集成它?我認為我們 Javascript 社區中的許多人已經變得過於依賴 `npm install ...` 來拼湊一個 web 應用程式。通常建置自己的元件,尤其是在 Svelte 中,可以減少整體花費的時間。我沒有資料可以證明,這是基於我個人的經驗。 不過,與此相關的是,對於任何願意重用開源元件的人來說,Svelte 元件的列表越來越多。 ## 正在找工作? 機會很多,請參閱 [https://sveltejobs.dev/](https://sveltejobs.dev/)。 Apple 的欺詐工程團隊正在[尋找 Svelte 開發人員](https://sveltejobs.dev/jobs/apple-senior-front-end-developer)(截至 2019 年 12 月)。 還要記住,與申請需要 React、Vue、Angular 等的工作相比,競爭要小得多。 # 然後,有 Sapper 來部署 Svelte 應用程式 開發應用程式只是整個蛋糕的一小部分——應用程式還需要部署。為此,Svelte 團隊提供了 [Sapper](https://sapper.svelte.dev/)。這本身就是一篇完整的帖子,所以現在請查看網站了解詳細訊息。 # 結論 每天,新的 Web 開發人員開始他們的旅程,許多人遇到的第一件事就是不確定首先要學什麼。我說未來就是簡單、快速的開發時間,我想不出比這更簡單、更快的事情了: ``` <script> let name = 'world'; </script> <style> h1 { color: blue; } </style> <h1>Hello {name}!</h1> ``` 以上分享,希望對您有幫助

軟體開發者推薦使用: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 應用程式列表,以及一種在您的系統中安裝和保持它們最新的方法。 希望其中一些對你們中的一些人有用:)

JavaScript 系列五:第7課 ── 學會 AJAX 與 data attribute 的結合

## 課程目標 學會結合 AJAX 與 data attribute 來製作應用程式 ## 課程內容 打造應用程式的時候,有些資料不會直接顯示在畫面上,但之後的其他動作會用到 這時可以把資料存在 data attribute 裡面 ``` <div data-email="don't know yet" data-phone="0987654321"> <span></span> <button onclick="showEmail()">show email</button> <button onclick="showPhone()">show phone</button> </div> <hr> <button onclick="load()">Load User</button> ``` ``` function showEmail() { alert(document.querySelector('div').dataset.email) } function showPhone() { alert(document.querySelector('div').dataset.phone) } function load() { fetch('https://fakestoreapi.com/users/1') .then(res => res.json()) .then(json => { const element = document.querySelector('div'); element.querySelector('span').textContent = json.username; element.dataset.email = json.email; element.dataset.phone = json.phone; }) } ``` 到 jsfiddle 跑跑看,按鈕到處點點看,就知道 data attribute 的用法了 非常簡單,寫 html 的時候,直接設定 `data-*` 屬性就是了 寫 js 的時候,直接存取 DOM 元素的 `dataset` 屬性就是了 如果 AJAX 撈到了大量資料,但畫面上只需先顯示一部分資料 那麼就可以用 data attribute 先把資料整理起來放著 之後要擴充這個應用程式,或者有同事接手維護,要拿資料時,就很方便,也可以避免一直重複發 AJAX 拿同樣的資料 ## 課後作業 接續上一課的作業,這次要改得更漂亮 點擊 Details 按鈕,本來是連續跳出三個 alert 實務上不可能用連續跳出 alert 來說明商品細節,太醜了 這次要拿掉 alert,改成跳出一個 modal 互動視窗元件, 你可以使用之前課程中,自己製作過的 modal 元件 也可以上網找套件,找一款現成的使用 --- 這個 modal 視窗要包含以下資訊 - 名稱 - 分類 - 描述 - 圖片 - 價格 請使用 data attribute 將資料存放在 `<li>` 元素 點擊 Details 按鈕時,再將這些資料撈出來,放進 modal 元件內 --- 做出以上功能,你就完成這次的課程目標了!

JavaScript 系列五:第6課 ── 學會 AJAX 與各種 HTTP 請求方法

## 課程目標 認識 AJAX 與不同的 HTTP 請求方法 ## 課程內容 HTTP 協定中,HTTP Request 有多種不同的方法 前面幾課的寫法,都是 HTTP GET 類型,這一課來接著談談更多不同的請求方法 繼續使用模擬電商網站的範例 API ### 使用 HTTP POST 新增一筆用戶資料 ``` fetch('https://fakestoreapi.com/users', { method: "POST", body: JSON.stringify({ email: '[email protected]', username: 'johnd', password: 'm38rmF$', name: { firstname: 'John', lastname: 'Doe' }, address: { city: 'kilcoole', street: '7835 new road', number: 3, zipcode: '12926-3874', geolocation: { lat: '-37.3159', long: '81.1496' } }, phone: '1-570-236-7033' }) }) .then(res => res.json()) .then(json => console.log(json)) ``` 在這個範例中,`fetch()` 函式的第二個參數是一個物件,把 method 屬性設定好,然後 body 代表 HTTP body 的內容 必須是字串,所以用 `JSON.stringify()` 把物件轉換成 JSON 字串 整段看不太懂沒關係,需要了解 HTTP 協定的細節才比較看得懂,現在就先照做即可 要注意我們是用模擬電商 API,一切都是模擬的 最後主機會回應一個新的用戶 ID,看起來是新增成功了,但實際上並沒有東西新增到資料庫喔~ ### 使用 HTTP PUT 更新一筆用戶資料 ``` fetch('https://fakestoreapi.com/users/7', { method: "PUT", body: JSON.stringify({ email: '[email protected]', username: 'johnd', password: 'm38rmF$', name: { firstname: 'John', lastname: 'Doe' }, address: { city: 'kilcoole', street: '7835 new road', number: 3, zipcode: '12926-3874', geolocation: { lat: '-37.3159', long: '81.1496' } }, phone: '1-570-236-7033' }) }) .then(res => res.json()) .then(json => console.log(json)) ``` 在這個範例中,去更新用戶 ID 為 7 的使用者資料 方法設定為 PUT,body 一樣放整個 JSON 字串 ### 使用 HTTP DELETE 刪除一筆用戶資料 ``` fetch('https://fakestoreapi.com/users/6', { method: "DELETE" }) .then(res => res.json()) .then(json => console.log(json)) ``` 在這個範例中,去刪除用戶 ID 為 6 的使用者資料 方法設定為 DELETE,不需要提供 body --- 實務上,API 設計時,有人偏好這種 GET POST PUT DELETE 都用到的寫法 有人則偏好只使用 GET 與 POST 撈資料一律都用 GET,除此之外,會更新到資料庫內容的動作,通通都用 POST 這屬於主觀偏好,沒有對錯問題,團隊討論後有共識即可 --- 上面的範例,用戶參數都是在網址最後加上 `/{ID}` 這種格式帶入 實務上,GET 參數也可能用 `?id={ID}` 這種格式 而在 POST 或其他類型的請求中,用戶參數也可能直接加在 `body: JSON.stringify({` 裡面的屬性之中 各種做法,都可以,一樣屬於主觀偏好,沒有對錯問題,團隊討論後有共識即可 ## 課後作業 接續上一課的作業,加上刪除按鈕 請翻閱 API 文件說明 https://fakestoreapi.com/docs 找出「刪除商品」的 API 把每個商品的 html 改成 ``` <li> <span>xxx</span> <button>Details</button> <button>Delete</button> </li> ``` 點擊 Delete 按鈕,就發送 API 出去 - 主機回應成功的話,就把整個 `<li>` 元素刪掉 - 主機回應失敗的話,就跳 alert 提醒用戶稍後再試 做出以上功能,你就完成這次的課程目標了!

JavaScript 系列五:第5課 ── 學會 AJAX 錯誤處理

## 課程目標 認識 AJAX 錯誤處理 ## 課程內容 在前一課,我們說過以下的話 > 有些任務現在還不會立刻執行,但我先把要執行的任務交待清楚,時間點到的時候,就執行 > 以 UI 動作來說,時間點就是 `onclick` 之時、`onchange` 之時 > 以 AJAX 動作來說,時間點就是 `拿到主機回應` 之時 實際上,AJAX 的時間點,除了 `拿到主機回應` 之時,還有一個,就是 `發現主機回應失敗` 之時 把原本的範例 ``` fetch('https://fakestoreapi.com/users/1') .then(res=>res.json()) .then(json=>console.log(json)) ``` 故意打錯字試試看,然後加上錯誤處理機制 ``` fetch('https://fakestoreapi.com/users1') .then(res=>res.json()) .then(json=>console.log(json)) .catch(error => { alert(error); }) ``` 就跟 `.then()` 函式把任務傳進去類似,`.catch()` 一樣是把任務傳進去,只是改傳「AJAX 失敗的時候要執行的任務」 --- 這邊只是舉例,才故意打錯字 實務上,AJAX 失敗可能是 - 主機故障、或者過度忙碌無法回應 - 呼叫 API 時,登入驗證資訊過期 - API 設計成有額度限制,用戶額度耗完了,被主機拒絕 - 用戶自己的網路斷線了(網頁打開時正常,但發送 AJAX 時已斷線) 等等很多可能,要看 API 主機是如何設計的 --- 實務上,`.catch()` 內要提醒使用者,剛才的動作失敗,請他重新嘗試 我個人通常就用 alert 跳一個訊息「抱歉,系統出現錯誤,請稍後重新嘗試。若持續出錯,請聯絡客服信箱」就結束了 但在公司的大型專案,需要更好 UX 的話,請與設計師討論後決定如何優雅地處理錯誤情境 ## 課後作業 接續前一課的作業,請加上錯誤處理機制 用 alert 跳出 `抱歉,請稍後重新嘗試。` 就好了 接著,請把電腦的 wifi 或有線網路,斷線 然後點擊「Load Products」按鈕,應該會看到錯誤提示訊息 做出以上功能,你就完成這次的課程目標了!

JavaScript 系列五:第4課 ── 學會 AJAX 基本原理

## 課程目標 認識基本的 AJAX 原理 ## 課程內容 這一課來認識大名鼎鼎的 AJAX 觀念 AJAX 全名 Asynchronous JavaScript and XML 簡單來說,就是「非同步從主機取得資料來更新網頁內容」的技術 舊式的網頁,都是瀏覽器向主機發送 HTTP 請求 -> 主機回應一大坨 html 內容 -> 瀏覽器顯示漂亮網頁給用戶看 因為是一次拿到一大坨 html 內容,我們說「網頁上全部內容都是同步取得」 現代的網頁,也是有很多頁面是這樣直接取得,但有更多功能,是依靠非同步取得資料之後來更新的 - 滑動到網頁下方,動態載入了更多貼文 - 對內容按讚,按讚成功網頁出現了小變化 - 聊天室與別人聊天,網頁也是一段一段文字更新 這些都是使用 AJAX 技術的例子 也就是先載入基本網頁內容,再接著根據需求,於不同時間點發送 HTTP 請求取得部份內容,所以叫做非同步 實務上,我們會說「這邊要發一個 AJAX 跟主機要資料」 --- 讓我們拿一個「模擬線上購物網站 API」來當作例子 https://fakestoreapi.com/ 發一個 AJAX 取得 ID 為 1 的用戶資料 ``` fetch('https://fakestoreapi.com/users/1') .then(res=>res.json()) .then(json=>console.log(json)) ``` 請在 jsfiddle 試試,看看結果 會看到一個包含信箱、ID、姓名、電話等等欄位的用戶個資,以物件的形式呈現 這邊使用了內建的 fetch 函式,參數放入要呼叫的 API 網址 接著使用 `.then()` 函式,由於是直接寫在後面,這相當於把 `fetch()` 回傳的東西,直接當成物件再接著呼叫 `.then()` 函式,然後再把結果當成物件再呼叫 `.then()` 一次 也就是跟這段一模一樣 ``` var result1 = fetch('https://fakestoreapi.com/users/1'); var result2 = result1.then(res=>res.json()); var result3 = result2.then(json=>console.log(json)); alert(result1) alert(result2) alert(result3) ``` 請在 jsfiddle 試試,會發現 console 顯示的個資一樣,這邊用三個 alert 觀察過程中的東西 會發現顯示三次 `[object Promise]`,這個 Promise 是一個進階觀念,這邊不細談,簡單講就是處理非同步請求的一種資料格式 `.then()` 參數傳進一個箭頭函式,這是省略大括號 `{}` 的箭頭函式寫法,其實就只是會自動回傳結果的函式寫法而已 但參數放了個函式,看起來有點怪,為何要這樣寫? --- 記得我們之前寫過的動態綁定 onclick 事件嗎? ``` <button id="my-btn">Click me</button> ``` ``` // 第一種寫法 function myFunction() { alert('你點擊了按鈕!'); } var btn = document.getElementById('my-btn'); btn.onclick = myFunction; ``` 網頁元素的事件處理,也是一種「非同步」程式設計 也就是我不確定「點擊」事件何時會發生,但我先「綁定」好事件發生時要做的任務,綁完就讓網頁正常呈現就好 上面的程式碼,可以改寫成這樣 ``` // 第二種寫法 var btn = document.getElementById('my-btn'); btn.onclick = () => { alert('你點擊了按鈕!'); } ``` 如果使用 jQuery,那還可以這樣改寫 ``` // 第三種寫法 $('#my-btn').click(() => { alert('你點擊了按鈕!'); }) ``` 第一種寫法,看起來像是:我先定義好函式,接著把函式名稱當作變數,綁定到 onclick 屬性 第二種寫法,看起來像是:onclick 這邊現場寫一個箭頭函式,把要執行的任務,當場交待清楚 第三種寫法,看起來像是:jQuery 提供的 `.click()` 函式,會負責把事件綁好,參數傳任務進去就對了 以上三種寫法,效果是完全一模一樣的! 所以你早就接觸過「非同步」程式設計了 也就是「有些任務現在還不會立刻執行,但我先把要執行的任務交待清楚,時間點到的時候,就執行」 以 UI 動作來說,時間點就是 `onclick` 之時、`onchange` 之時 以 AJAX 動作來說,時間點就是 `拿到主機回應` 之時 像這種不是馬上執行的動作,在 JavaScript 領域,我們習慣用「寫一段函式定義當作參數傳進去」來表達! --- 回頭看一下我們的範例 ``` fetch('https://fakestoreapi.com/users/1') .then(res=>res.json()) .then(json=>console.log(json)) ``` 因為 fetch 第一個回傳的結果,代表的是一個 `HTTP 回應物件`,這個回應物件的 HTTP body 是實際的 JSON 內容,可以用 `.json()` 函式取得內容 所以第二個 `.then()` 的參數,才是我們真正想做的事情 看不懂沒關係,我們多看幾個例子吧 取得全部用戶個資的 AJAX。觀察 console 結果,會看到一個陣列,內含大量個資物件 ``` fetch('https://fakestoreapi.com/users') .then(res=>res.json()) .then(json=>console.log(json)) ``` 取得五筆用戶個資,也是拿到陣列 ``` fetch('https://fakestoreapi.com/users?limit=5') .then(res=>res.json()) .then(json=>console.log(json)) ``` 以上內容,全部通通看不懂沒關係,畢竟,需要多了解一些 HTTP 協定與術語,比較好理解 你就先照做就好:要發 AJAX,就用 `fetch()` 函式,接著第一個 `then()` 要執行 `.json()` 函式,然後第二個函式才是你真正要執行的任務! ## 課後作業 請使用 https://jsfiddle.net/ 請使用「模擬線上購物網站 API」 https://fakestoreapi.com/ 假設正在開發一個讀取全部商品資料的頁面 用以下 html 為基礎 ``` <button>Load Products</button> <hr> <ul></ul> ``` 點擊按鈕,發送 AJAX 到 https://fakestoreapi.com/products 請求全部商品資料 拿到資料之後,將每筆資料用以下格式呈現,塞進 `<ul>` 元素裡面 ``` <li> <span>xxx</span> <button>Details</button> </li> ``` xxx 是商品名稱。點擊 Details 按鈕,連續跳出三個 alert,分別顯示 `id` `category` `description` --- 請注意,在 for 迴圈裡面綁定 onclick 事件的時候,for 迴圈的參數請加上 `const` 舉例來說,請這樣寫 ``` for (const product of json) { ``` 請「不要」這樣寫 ``` for (product of json) { ``` 否則,在迴圈裡面的 onclick 事件,執行起來會有 bug 原因跟上一課提到的 Hoisting 現象有關 我認為這是 JavaScript 的設計失敗,所以詳細原因我不想說明 這是屬於上個世代 JS 工程師的痛苦回憶,這一代的 JS 工程師不需要經歷 現在就用 ES6 語法,宣告變數一律記得加上 `const` 或 `let` 就對了 --- 做出以上功能,你就完成這次的課程目標了!

新手不用急著學 TypeScript,不如先把 JavaScript 學熟練

> 為什麼有些 JavaScript 工程師沒在用 TypeScript 呢?原因有哪些? 我在推特問大家:為什麼你還沒用 TypeScript? ![](https://res.cloudinary.com/practicaldev/image/fetch/s--By6b0ozU--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3uto8rrbud9yv303gs5b.png) 這篇文章簡單整理大家的答案。 原文出處:https://dev.to/codewithvoid/ive-got-99-problems-but-learning-typescript-aint-one-o70 讓我們開始吧。 ## 先征服 JavaScript 👨‍🏫️ 很多新手和初學者給出了“我還在學習 JS”的原因。 可以理解,他們現在不想承擔超過他們可以吸收的東西。 他們中的大多數人有興趣在未來嘗試一下,而有些人則在尋求指導,看看是否應該這樣做。 ## 純 JavaScript 就很夠用 👌 已經在使用 JS 的開發人員有一個問題 → “為什麼需要?”。 他們不打算遷移過去,因為有一個用 JavaScript 編寫的大型程式庫、易於調試,或者僅僅是因為他們對 JS 感到滿意,因為它可以完成工作。 他們的座右銘是:“如果夠用,就不要碰它”。 ## 對不起,晚點再考慮🕒 一些有經驗的 JS 開發人員已經計劃學習 TypeScript,但認為合適的時機還沒有到來。 與不願意遷移的開發人員不同,這些開發人員看到了 TypeScript 的價值。只是他們還沒有找到合適的專案,這證明了學習曲線的確存在。 此外,他們希望工具(如支持在瀏覽器中本地運行 TS 程式碼)在未來得到改進。 ## 要看情況使用🧐 一些開發人員花時間學習了 TypeScript,但並沒有在每個專案中都使用。 根據他們的說法,主要原因是: - 需要跟團隊一起 - 應用程式已上線 - 程式庫太龐大 他們說“對於個人專案和簡單的應用程序,TypeScript 是一種矯枉過正”。 ## ECMA 即將到來🏁 最後,一些回應是關於 ECMA 6 已經支持足夠的現代性,可在 JS 中編寫乾淨的代碼。 這些開發人員建議,如果你足夠了解 JavaScript 並使用圍繞它構建的工具,你就不需要 TypeScript。 此外,他們希望 TypeScript 中的有用功能最終會包含在原生 JavaScript 中,所以為什麼要費心研究 2 個學習曲線。 ## 總結📝 您對 TypeScript 的心得是什麼?歡迎在留言處分享。

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

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

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