Peiyun Lee
    • 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
    • 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 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
    ###### tags: `前端技能樹` # React + Redux = React-redux >前情提要:在前面的文章[有了Redux,狀態管理沒煩惱](),學到了如何在 Redux 透過 Action 管理更新所有的 State。接下來就讓我們學習如何在 React 中使用 Redux 來處理資料狀態。 Redux 是一個獨立的狀態管理函式庫,它可以搭配原生 Javascript 直接撰寫出一個應用程式,也可以與其他框架像是 React、Angular 一起運作。**而當 Redux 與 React 結合時,會使用 React-redux 這個延伸的函式庫,有效的來解決 React Component 間 State 複雜化的問題**。 ## 安裝React-redux Fork 一份之前所使用的[React - 計時器範例程式碼](https://codesandbox.io/s/21ithome-react3-fhcsu),基於這個架構從頭來使用 React-redux。 ![](https://i.imgur.com/kvflcV5.gif) React-redux 前面建置步驟基本上跟單純使用 Redux 一樣,要事先建立 Action、Reducer、Store,所以我們直接貼上前篇建立好的三份程式碼 actions.js、reducer.js、store.js,裡面包含了 Redux 應用在計數器的內容。 actions.js ```jsx= export const ADD_SCORE = "ADD_SCORE"; export const REDUCE_SCORE = "REDUCE_SCORE"; // action creator export function addScore(idx) { return { type: ADD_SCORE, payload: { idx } }; } export function reduceScore(idx) { return { type: REDUCE_SCORE, payload: { idx } }; } ``` reducer.js ```jsx= import { ADD_SCORE, REDUCE_SCORE } from "./actions"; const initialState = { members: [ { name: "May", score: 0 }, { name: "Julia", score: 0 }, { name: "Selina", score: 0 } ] }; export default function appReducer(state = initialState, action) { switch (action.type) { case ADD_SCORE: { let new_members = state.members; new_members[action.payload.idx] = { ...new_members[action.payload.idx], score: new_members[action.payload.idx].score + 1 }; return { members: new_members }; } case REDUCE_SCORE: { let new_members = state.members; new_members[action.payload.idx] = { ...new_members[action.payload.idx], score: new_members[action.payload.idx].score - 1 }; return { members: new_members }; } default: return state; } } ``` store.js ```jsx= import { createStore } from "redux"; import rootReducer from "./reducer"; const store = createStore(rootReducer); export default store; ``` ## 傳遞 Store 接著就讓我們正式將 React 與 Redux 結合,我們首先要做的就是讓 React Component 知道 Store,才能讀取資料和調用動作,所以就透過在 Root component 使用 ```<Provider>``` 的方式來傳遞 Store。 ```jsx= ... import { Provider } from "react-redux"; import store from './store' ReactDOM.render( <StrictMode> <Provider store={store}> <App /> </Provider> </StrictMode>, rootElement ); ``` ## 從 Store 讀取狀態 要從 Store 讀取狀態,可以使用 ```useSelector``` 這個方法,直接提取 Redux Store 中的狀態數據到指定的元件中。並且它會對之前的選擇器回傳值和當前的回傳值進行比較,如果不同,相關的組件就會重新渲染。 App.js ```jsx= import { useSelector } from "react-redux"; export default function App() { const members = useSelector((state) => state.members); return ( <div className="App"> ... {members.map((member) => ( <Member key={member.name} idx={index} /> ))} </div> ); } ``` Member.js ```jsx= ... import { useSelector } from "react-redux"; export default function Member(props) { const members = useSelector((state) => state.members); return ( <div className="member"> <h2>{members[props.idx].name}</h2> <div>{members[props.idx].score > 0 ? "PASS" : "FAIL"}</div> <Counter idx={props.idx} /> </div> ); } ``` Counter.js ```jsx= import { useDispatch, useSelector } from "react-redux"; import { addScore, reduceScore } from "../actions"; export default function Counter(props) { const score = useSelector((state) => state.members[props.idx].score); return ( <div className="Counter"> <h3>{score}</h3> ... {score > 0 && ( <button>minus</button> )} </div> ); } ``` ## 調用動作 完成從 Store 讀取資料狀態後,最後一個步驟就是要可以在組件中調用動作,來修改 State 的值。我們可以透過 ```useDispatch()``` 這個方法,發動指定的 Action 到 Reducer 中更新 State。 Counter.js ```jsx= ... import { useDispatch, useSelector } from "react-redux"; import { addScore, reduceScore } from "../actions"; export default function Counter(props) { const score = ... const dispatch = useDispatch(); return ( <div className="Counter"> ... <button onClick={() => dispatch(addScore(props.idx))}>Plus</button> {score > 0 && ( <button onClick={() => dispatch(reduceScore(props.idx))}>minus</button> )} </div> ); } ``` *** ## 小結 在 React 中使用 Redux 的 React-redux 基本上就是這樣運作的,以往在 React 中需要透過提升 State 層級才能在 Component 間共同使用狀態,結合 Redux 集中狀態管理的功能,就能有效的管理複雜的 State,彌補了 React 框架的缺點更提升它的優勢。 [範例程式碼](https://codesandbox.io/s/21ithome-react-redux-sm4cy) 如果文章中有錯誤的地方,要麻煩各位大大不吝賜教;喜歡的話,也要記得幫我按讚訂閱喔❤️ ### 參考資料 - [Redux Document](https://redux.js.org/introduction/getting-started)

    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