M
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # React 筆記 ## Popular react tools - reselect - Material UI - immutable js ## Build Workflow ![](https://i.imgur.com/LV66PYa.png) ## Create react app 1. 下載npm後,在終端機輸入:`npm install create-react-app -g ` 其中g表示globally,若是MAC用戶可能需要在前面+`sudo` 2. 在終端機輸入`create-react-app myapp --scripts-version 1.1.5` 表示要創建一個名為myapp的react app。 3. 進入創建好的react app資料夾,在終端機輸入`npm start`就可以看到app在browser上執行了。 > NOTES: 新版的 create react app 方法不希望我們下載 create-react-app 套件,反之應該直接使用以下指令: ``` $ npx create-react-app {my-app} ``` Reference: [create react app 官方文件](https://create-react-app.dev/docs/getting-started/) ## The fold structure node_modules (自動生成的,不要動它) package.json (記錄我們會使用哪些套件以及版本) public (儲存) src (我們會修改到的地方) ## JSX JSX 並不是 html,而是一個能讓我們在 js 上寫「類似 html 語法」的功能。 舉例來說: ```javascript= return ( <div className="App"> <h1>Hi, I'm Malik</h1> </div> ); ``` 實際上是 React 在背後操作,其語法完全等價於: ```javascript= return React.createElement('div', {className: 'App'} ,React.createElement('h1',null,'Hi, I\'m Malik')) ``` 因此事實上 JSX 幫我們省略麻煩的語法 ## Creating a functional components ## Radium 一個幫助我們styling components的套件 ## Some resources: create-react-app: https://github.com/facebookincubator/create-react-app Introducing JSX: https://reactjs.org/docs/introducing-jsx.html Rendering Elements: https://reactjs.org/docs/rendering-elements.html Components & Props: https://reactjs.org/docs/components-and-props.html Listenable Events: https://reactjs.org/docs/events.html # Component Deep Dive ## A better project structure - 建立兩個資料夾:Containers & Components - Components 如果有 list 的關聯(e.g. Persons 由 Person 構成),可以包在同個路徑下(Persons資料夾中有Peesons.js與Person資料夾)。 - Use as many function components as possible ; let container be as lean as possible - ## Class-based vs Functional Components ![](https://i.imgur.com/Zqk4SEw.png) ## Component Lifecycle ![](https://i.imgur.com/ViPba8j.png) We've got these methods which we can add to any class-based component and React will execute them for us and they will run at different points of time and we can do different things with them, to for example fetch data from the web or to do some cleanup work before a component is removed from the DOM. ### Creation ![](https://i.imgur.com/oN8rqSb.png) 搭配課程影片:[Components lifecycle in action](https://www.udemy.com/course/react-the-complete-guide-incl-redux/learn/lecture/13556268#overview) ### Update ![](https://i.imgur.com/ewmuBBj.png) 搭配課程影片:[Components update lifecycle (props)](https://www.udemy.com/course/react-the-complete-guide-incl-redux/learn/lecture/13585862#overview) ShouldComponentUpdate return True => 改變 state,False 則不會改變 state。 ### Using shouldComponentUpdate for Optimization 非常重要的主題,藉由在 shouldComponentUpdate 階段比較 state 是否有變化,決定是否要 re-render 該 component。若 state 沒有變化,則程式僅會執行到 shouldComponentUpdate 而不再繼續執行下去。 可利用 Google Chrome 開發者工具中的 more tools 中的 rendering,他能顯示不同行為下哪些 components 被 re-render。 限制:shouldComponentUpdate 僅有 class-based component 可使用。 搭配課程影片: 1. [Using shouldComponentUpdate for Optimization](https://www.udemy.com/course/react-the-complete-guide-incl-redux/learn/lecture/13556300#overview) 2. [When should you optimize?](https://www.udemy.com/course/react-the-complete-guide-incl-redux/learn/lecture/13556304#overview) 3. [PureComponents instead of shouldComponentUpdate](https://www.udemy.com/course/react-the-complete-guide-incl-redux/learn/lecture/13556312#overview) ### Optimizing Functional Components with React.memo() 上一講提到僅有 class-based component 可使用shouldComponentUpdate,在 function-based component 中則是在 export default {component名稱} 時可增加 React.memo()。 例: ```javascript= export default React.memo(cockpit) ``` You can wrap your export, so your entire component here in the cockpit.js file with React memo. This basically uses memoization which is a technique where React will memorize,so basically store a snapshot of this component and only if its input changes, it will re-render it and otherwise if its inputs do not change and some parent component wants to update this cockpit component, React will give back that stored component. **小結** 基本上,若上層 container 傳給 child component 作為 props 的 state 有改變,則 component 的程式碼就會執行(即使 component 並不需要、也並沒有任何的更新) 上層 component 的 props 傳遞進來若跟先前的 props 有「任何一點」發生改變,預設上會使這層 component 重新 render。然而,有時候該 component 程式碼不需要重新執行(不需要重新 render ),則我們可以藉由在shouldComponentUpdate 或是 React.memo() 去檢查 props 中「我們只在意的的某個部分」是否被改變,若沒被改變,就回傳 false,讓後續的程式碼不會執行,就不會重新 render。 以上的觀念需要釐清:程式碼「執行」不代表DOM會被更新,即使React re-render,但若 render 前後的狀態不同,DOM不會被修改。我們在此只是希望能在效能上做得更好:若component並未做任何改變,就連render都不要(程式碼不要執行)。 ### Hoe react update the DOM ![](https://i.imgur.com/x623yze.png) ## Rendering Adjacent JSX Elements 過去我們提到在 retrun JSX 時必須有一個 root element(如:div 把所有東西包起來)。事實上不用這麼麻煩,可以改用high order component 去做到這件事情。 ```javascript= const aux = (props) => { return props.children } export default aux ``` 注意,我們甚至不需用import React 因為我們沒有用到任何JSX,而children 是 React 幫我們設的保留字。若我們懶得創像是「Aux」這樣的component,則可以在 App.js (container)上這樣寫: ```javascript import {Fragment} from 'React' ``` Fragment 是 React 預設幫我們提供這類服務的一個component,可以直接拿來用。 搭配課程影片: 1. [Rendering Adjacent JSX Elements](https://www.udemy.com/course/react-the-complete-guide-incl-redux/learn/lecture/13556324#overview) 2. [Using React.Fragment](https://www.udemy.com/course/react-the-complete-guide-incl-redux/learn/lecture/13556326#overview) ## Higher Order Components (HOC) HOC 有兩種寫法: ```javascript= const withClass = props => ( <div className = {props.classes}>{porps.children}</div> ) //回傳一個 JSX,因此withClass在此是一個component export default withClass const withClass = (WrappedComponent, className) =>{ return props => ( <div className = {className}> <WrappedComponent {...props}/> </div> ) //在函式中回傳一個函式,因此withClass在此單純是一個函式而不是component。而若我們有props要傳時則需要加入{...props}。 }; export default withClass ``` 在 HOC 中可能會多加一些 HTML / CSS styling / Javascript logic 搭配課程影片: 1. [Higher Order Components (HOC) - Introduction](https://www.udemy.com/course/react-the-complete-guide-incl-redux/learn/lecture/13556328#content) 2. [Another Form of HOCs](https://www.udemy.com/course/react-the-complete-guide-incl-redux/learn/lecture/13556330#content) 3. [Passing unknown props](https://www.udemy.com/course/react-the-complete-guide-incl-redux/learn/lecture/13556332#content) ## Setting State Correctly (VERY IMPORTANT) 當我們想要更新 state dependent on old state 時: e.g. State 有一個 counter 更新時會將原先的 counter +1 ```javascript= //錯誤的寫法: this.setState({ persons: persons changeCounter: this.state.changeCounter + 1 }) //正確的寫法:呼叫一個 function this.setState( (prevState,props) => { return ( { persons: persons changeCounter: prevState.changeCounter + 1 } ) }) ``` 另一個案例: ```javascript= // 錯誤的寫法 sideDrawerToggleHandler = () => { this.setState({showSideDrawer: !this.state.showSideDrawer}); } //正確的寫法: sideDrawerToggleHandler = () => { this.setState( (prevState) => { return { showSideDrawer: !prevState.showSideDrawer} } ); } ``` 之所以會出錯是因為 asynchronous nature of setState。 搭配課程影片:[Setting State Correctly](https://www.udemy.com/course/react-the-complete-guide-incl-redux/learn/lecture/13556334#content) ## Using PropTypes 當我們與他人合作大型專案時,為了防止他人使用自己的 code 時在傳遞props 時傳錯型態(e.g. props.age 必須是 int 卻傳入了 string),我們可以明確寫好每個 props 是什麼型態。在此可引用一個套件:prop-types 在終端機輸入: ``` $ npm install --save prop-types ``` e.g. ```javascript= import PropTypes from 'prop-types'; // some code Persons.propTypes = { click: PropTypes.func, name: PropTypes.string, age: PropTypes.number, changed: PropTypes.func }; ``` 搭配課程影片:[Using PropTypes](https://www.udemy.com/course/react-the-complete-guide-incl-redux/learn/lecture/13556336#content) ## Context 當我們想要把 props 從 A 傳遞到 D 但又不想經過中間的 B,C 時,就需要 context 的幫助。 創建一個 context 資料夾 ## Manifest.json Manifest Json 提供了應用程式相關的資訊(像是名稱、作者、圖示、描述)。 manifest 的功用是將 Web 應用程式安裝到設備的主畫面,為使用者提供更快速的訪問和更豐富的體驗。 * [Manifest Json](https://medium.com/front-end-augustus-study-notes/pwa-minifest-6943b5fc65a9) ## Route - [React-Router-DOM](https://ithelp.ithome.com.tw/articles/10226370)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully