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: `前端技能樹` # Todolist with React (3) >在上一章[Todolist with React (2)](),完成所有樣式設定後,現在就讓我們在 React 中加入 Redux,使用 React-redux 動態產生任務清單。 ### 建立架構 將狀態資料分成 Todo 任務資料和 Filter 篩選器資料,事先建立好 Store、Reducer、Action 的檔案。 ``` src ├── ... ├── actions ├── ActionTypes.js ├── filter.js ├── todos.js ├── reducer ├── filter.js ├── index.js ├── todos.js ├── store.js ``` - actions:ActionTypes.js 負責定義 Todo 和 Filter 的所有 Action - reducer:index.js 會整合 Todo 和 Filter 的 Reducer - store.js:處理 Store ## 初始化 Task 資料 首先先處理渲染任務資料的部分,在 todos.js 定義出原始的任務資料 ```initialTasks```,包含任務的名稱和狀態,方便我們產生清單。 reducer/todos.js ```javascript= const initialTasks = [ { taskName: "task1", isCompleted: false }, { taskName: "task2", isCompleted: true }, { taskName: "task3", isCompleted: false }, ]; ``` ### Todo Reducer 繼續在同一份程式碼建立 Todo Reducer,State 參數的預設值為之前定義的 ```initialTasks```,目前尚未定義 Action,直接回傳當前原本的 State。 reducer/todos.js ```javascript= import * as types from '../actions/ActionTypes'; export default function todos(state = initialTasks, action) { switch (action.type) { default: return state; } } ``` 因為我們會有兩份 Reducer,要用 ```combineReducers``` 將兩者合併,目前還沒做到 Filter Reducer,這邊就先填上 Todo Reducer。 reducer/index.js ```javascript= import { combineReducers } from 'redux'; import todosReducer from './todos'; const todoApp = combineReducers({ todosReducer }); export default todoApp; ``` ### Create Store 再來建立 Store 引入 rootReducer,透過 ```<Provider>``` 的方式來傳遞 Store 讓網頁能夠讀取更新狀態。 src/store.js ```javascript= import { createStore } from "redux"; import rootReducer from "./reducer/index"; const store = createStore(rootReducer); export default store; ``` src/index.js ```javascript= ... import { Provider } from "react-redux"; import store from "./store"; ReactDOM.render( <React.StrictMode> <Provider store={store}> <App /> </Provider> </React.StrictMode>, ... ); ``` ### Render TaskItem 將 Store 傳入 React Component 後,TaskList Component 就可以使用 ```useSelector``` 取得任務清單。原本我們是直接複製三個 ```<TaskItem />``` 產生三個任務,修改成利用 ```forEach``` 讀取 Store 的動態產生任務,並且把任務資料和編號 ```task={{ ...item, idx: index }}``` 傳入 ```<TaskItem />```: components/TaskList.js ```javascript= ... import { useSelector } from "react-redux"; function TaskList() { const tasks = useSelector((store) => store.todosReducer); const renderItems = () => { let list = []; tasks.forEach((item, index) => { list.push( <TaskItem key={item.taskName} task={{ ...item, idx: index }} /> ); }); return list; }; return ( <Wrapper> ... <TaskItemContainer>{renderItems()}</TaskItemContainer> </Wrapper> ); } ``` components/TaskItem.js ```javascript= function TaskItem(props) { return ( <Container> <CheckBox type="checkbox" checked={props.task.isCompleted} /> <TaskName>{props.task.taskName}</TaskName> <Button>Delete</Button> </Container> ); } ``` ![](https://i.imgur.com/pd95vR9.png) ## 新增 / 刪除 Task 所有任務都能動態渲染後,再來處理任務新增 / 刪除的功能,在 ActionTypes.js 定義 ```ADD_TASK``` 和 ```DELETE_TASK```,這樣可以統一方便管理所有 Action。 actions/ActionTypes.js ```javascript= export const ADD_TASK = 'ADD_TASK'; export const DELETE_TASK = 'DELETE_TASK'; ``` ### 新增 Task Step1:建立 Action Creator 產生新增 Task 的動作 Function ```addTask```,並取得新增的任務名稱 ```taskName```。 actions/todos.js ```javascript= import * as types from './ActionTypes'; export function addTask(taskName){ return { type: types.ADD_TASK, taskName }; } ``` Step2:處理 Todo Reducer,讀取 action.type 為 ```ADD_TASK``` 時,儲存新任務的資料並回傳新的 State。 reducer/todos.js ```javascript= import * as types from '../actions/ActionTypes'; const initialTasks = ... export default function todos(state = initialTasks, action) { switch (action.type) { case types.ADD_TASK: return [ ...state, { taskName: action.taskName, isCompleted: false, }, ]; default:... } } ``` Step3:完成 Action 和 Reducer 的設定後,在 AddTask Component 利用 ```useDispatch()``` 來調用 Action。點擊 ```<AddBtn />``` 後呼叫 ```handleClick()```,處理新增任務的程式。 components/AddTask.js ```jsx= import { useDispatch } from "react-redux"; function AddTask() { const dispatch = useDispatch(); const [newTask, setnewTask] = ... const handleChange = ... const handleClick = (event) => { if(newTask === "") return; //檢查有沒有輸入任務名稱 dispatch(actions.addTask(newTask)); setnewTask(""); }; return ( <Wrapper> ... <AddBtn onClick={() => handleClick()} > <img src={addIcon} alt=""/> </AddBtn> </Wrapper> ); } ``` ![](https://i.imgur.com/nJeLWW9.gif) ### 刪除 Task Step1:刪除 Task 的部分也大同小異,第一步建立 Action Creator 產生刪除 Task 的動作 Function ```deleteTask```,並取得要刪除的任務索引值 ```idx```。 actions/todos.js ```javascript= export function deleteTask(idx){ return { type: types.DELETE_TASK, idx }; } ``` Step2:處理 Todo Reducer,讀取 action.type 為 ```DELETE_TASK``` 時,刪除該任務的資料並回傳的新 State。 actions/todos.js ```javascript= export default function todos(state = initialTasks, action) { switch (action.type) { case types.ADD_TASK:... case types.DELETE_TASK: return [ ...state.slice(0, action.idx), ...state.slice(action.idx + 1) ]; default:... } } ``` Step3:完成 Action 和 Reducer 的設定後,在 TaskItem Component 利用 ```useDispatch()``` 來調用 Action。點擊 ```<Button/>``` 後直接呼叫 ```deleteTask()```,傳入要刪除的任務索引值。 components/TaskItem.js ```jsx= import { useDispatch } from "react-redux"; function TaskItem(props) { const dispatch = useDispatch(); return ( <Container> ... <Button onClick={() => dispatch(actions.deleteTask(props.task.idx))}> Delete </Button> </Container> ); } ``` ![](https://i.imgur.com/GyvOnNJ.gif) *** ## 小結 今天完成了渲染任務清單、和任務新增刪除的動作,在下一篇文章,我們會繼續完成最後一個部分 — Filter 篩選器,那我們就明天見囉! [範例程式碼](https://github.com/peiyunlee/ithome-21ironman-todolist) 如果文章中有錯誤的地方,要麻煩各位大大不吝賜教;喜歡的話,也要記得幫我按讚訂閱喔❤️

    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