RZ-Huang
    • 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
    • Engagement control
    • 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 Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control 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
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # 初探 React 背後的運作機制 ###### tags: `javascript`、`react` ## JSX 的真面目 給個範例,今天有 `app.js` 和 `todo.js` 兩個檔案。 `app.js` 檔案程式碼: ```jsx= import React, { Component } from 'react' import Todo from './todo.js' // Parent Component class App extends Component { render() { return ( <div> <Todo /> </div> ) } } export default App ``` `todo.js` 檔案程式碼: ```jsx= import React, { Component } from 'react' // Children Component export default function Todo() { return <h1>hello</h1> } ``` 然後會發現 `todo.js` 程式碼都沒用到 React 或 Component,這樣第 1 行 `import` 就不用寫了不是嗎?把程式碼變成這樣: ```jsx= // Children Component export default function Todo() { return <h1>hello</h1> } ``` 結果畫面 render 失敗,跑出了錯誤: ![](https://i.imgur.com/nR7rrrk.png) 說 React 不存在,點進去 `todo.js:4` 看看程式碼: ![](https://i.imgur.com/ZIN8len.png) 是 `return React.createElement("h1", null, "hello");` 這段程式碼出了錯,有使用到 `React`,因此才會出錯。 而 `React.createElement("h1", null, "hello")` 就等同於 JSX 語法的 `<h1>hello</h1>`,所以你如果把 JSX 語法寫成 React 的語法也可以,因為它就是 JSX 語法底下在運作的語法。只是一般來說都會使用 JSX 語法來撰寫,因為比較方便撰寫與易讀。 ## React 的渲染機制 與 Virtual DOM 在 jQuery 當中,如果我們寫一個 function 專門 render 畫面的,只要一變更資料就 call 這個 function,雖然很方便在更新資料時不用使用太多 DOM 節點的操作只管資料有沒有傳到相對應的變數,但今天如果我們有好幾百個元素在 專門 render 的 function 當中,若只更改一個元素資料,按照提升效能的角度來說,理當只在畫面中更改那一個元素就好,但是在 render 的 function 當中不會管這麼多,只要資料變更就會是整個畫面好幾百個元素重新 render,因此變成有很多多餘的動作拖垮網站效能。 那 React 的 `render` function 呢?也是這樣子嗎? 我們舉個例子: jQuery 的寫法: ```javascript= function render() { $('ul').empty(); $('ul').append(` <div> 123 </div> `); } ``` React 的寫法: ```jsx= class App extends Component { // 看這個 render function render() { return ( <div> 123 </div> ) } } ``` 單看 `render` function 裡面放的元素,會發現說和 jQuery 所寫的內容並無不同,這樣是否也代表 React 的 `render` function 也是一更新資料就會全部 render 一遍? 答案是否定的,因為 React 的 render 底層,或者說在 render 的時候還有一層機制叫做 Virtual DOM,長這樣: ![](https://i.imgur.com/NO2bR4L.png) 圖片來源:https://auth0.com/blog/face-off-virtual-dom-vs-incremental-dom-vs-glimmer/ 這個 Virtual DOM 是一個機制,幫我們把 DOM 結構存到記憶體當中,只要 DOM 因 state 有所變化就會再建立另外一個 DOM 副本存到另外一個記憶體當中,接著再以最小操作化去觀察兩個不同記憶體之間的 DOM 的差別,然後再把這個差別 Patch 到實體的 DOM 上面去。 也因為有 Virtual DOM 的機制,可以讓 React 的 `render` function 在更新 DOM 結構的時候,不會全部的 DOM 結構都 render,在 render 的時候只會更新有不同的地方。 拿上面的 React 程式碼來看,`render` 的部份在 Virtual DOM 類似這樣的結構: ```jsx= { tag: 'div', props: null, children: 123 } ``` 如果 `render` 內容改成: ```jsx= <div> 456 </div> ``` 那 Virtual DOM 就類似變成這樣: ```jsx= { tag: 'div', props: null, children: 456 } ``` 而這兩個以 object 組成的資料,僅有 `children` 的內容從 '123' 變成 `456`,因此,`render` 就只會更新這個 `children` 的內容而已,其它的 DOM 結構都不會去動也不會重新 render。 #### 延伸資料 1. [從頭打造一個簡單的 Virtual DOM](https://blog.techbridge.cc/2019/02/04/vdom-from-scratch/) ## Pure component 與 Immutable data 請參考這篇:https://github.com/aszx87410/blog/issues/26

    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