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 (4) >在上一章[Todolist with React (3)](),使用 React-redux 完成了渲染任務清單、和任務新增刪除的動作,就讓我們繼續完成最後一個部分 — Filter 篩選器,控制任務清單的顯示。 ![](https://i.imgur.com/G8q91sj.gif) >切換上方的 Filter,可以切換對應的任務清單 ## 初始化 Filter 首先先處理顯示篩選器按鈕的部分,被選擇的按鈕要顯示 Selected (黃底) 的樣式,總共會有三種狀態 ```SHOW_ALL```、```SHOW_TODO```、```SHOW_DONE```。 ### Filter Reducer 在 filter.js 定義控制 Filter 的 Reducer,State 參數的預設值為 ```SHOW_ALL```,目前尚未定義 Action,直接回傳當前原本的 State。然後要在 index.js 裡整合 Filter Reducer。 reducer/filter.js ```javascript= import * as types from '../actions/ActionTypes'; export default function filter(state = 'SHOW_ALL', action) { switch (action.type) { default: return state; } } ``` reducer/index.js ```javascript= ... import filterReducer from './filter'; const todoApp = combineReducers({ filterReducer, todosReducer }); ``` ### 顯示 Selected Filter 因為在 TaskList Component 內也會需要 Filter 的狀態來顯示對應的任務清單,所以我們在 TaskList Component 使用 useSelector 取得目前的 Filter 狀態,再把它傳入 Filter Component。 components/TaskList.js ```jsx= ... import { useSelector } from "react-redux"; function TaskList() { ... const filter = useSelector((store) => store.filterReducer); const renderItems = ... return ( <Wrapper> <Filter selected = {filter}/> ... </Wrapper> ); } ``` 利用 Styled-components 根據 Props 可以改變樣式的功能,只要按鈕是 Selected 的狀態,傳入的 ```active``` 就是 ```true```,會切換背景顏色變成黃色。 components/Filter.js ```jsx= const Button = styled.div` background-color: ${(props) => (props.active ? "#ffc236" : "#bebebe")}; ... `; function Filter(props) { return ( <ButtonContainer> <Button active={props.selected === "SHOW_ALL"}> ALL </Button> <Button active={props.selected === "SHOW_TODO"}> TODO </Button> <Button active={props.selected === "SHOW_DONE"}> DONE </Button> </ButtonContainer> ); } ``` ## 控制 Filter 可以顯示被選擇的按鈕後,接下來要新增 Filter 切換的功能,在 ActionTypes.js 定義 ```SET_FILTER``` 動作。 actions/ActionTypes.js ```javascript= ... export const SET_FILTER = 'SET_FILTER'; ``` ### 切換 Filter Step1:建立 Action Creator 產生設定 Filter 的動作 Function setFilter,並取得切換的 filter 名稱。 actions/filter.js ```javascript= import * as types from './ActionTypes'; // action creator export function setFilter(filter){ return { type: types.SET_FILTER, filter }; } ``` Step2:處理 Filter Reducer,讀取 action.type 為 SET_FILTER 時,直接回傳新的 Filter 狀態。 reducer/filter.js ```javascript= import * as types from '../actions/ActionTypes'; export default function filter(state = 'SHOW_ALL', action) { switch (action.type) { case types.SET_FILTER: return action.filter; default: return state; } } ``` Step3:完成 Action 和 Reducer 的設定後,在 Filter Component 利用 ```useDispatch()``` 來調用 Action。點擊 <Button /> 後直接呼叫 setFilter(),傳入對應的篩選器名稱。 components/Filter.js ```jsx= import { useDispatch } from "react-redux"; function Filter(props) { const dispatch = useDispatch(); return ( <ButtonContainer> <Button active={...} onClick={() => dispatch(actions.setFilter("SHOW_ALL"))} > ALL </Button> <Button active={...} onClick={() => dispatch(actions.setFilter("SHOW_TODO"))} > TODO </Button> <Button active={...} onClick={() => dispatch(actions.setFilter("SHOW_DONE"))} > DONE </Button> </ButtonContainer> ); } ``` ![](https://i.imgur.com/D9HXAzp.gif) ### 渲染對應的 Task 切換篩選器的同時,下方的任務清單也要可以根據狀態切換對應的列表,我們只在 ```forEach``` 裡面新增 ```if``` 條件式判斷,總共會有三種情況: - ```filter === "SHOW_ALL"```:當 Filter 是 ```SHOW_ALL``` 時,判斷式永遠為 true,顯示該任務。 - ```filter === "SHOW_TODO" && !item.isCompleted```:當 Filter 是 ```SHOW_TODO``` 時,任務的狀態 ```isCompleted``` 要是 ```false```,判斷式會為 true,才能顯示該任務。 - ```filter === "SHOW_DONE" && item.isCompleted```:當 Filter 是 ```SHOW_DONE``` 時,任務的狀態 ```isCompleted``` 要是 true,判斷式會為 true,才能顯示該任務。 components/TaskList.js ```jsx= function TaskList() { ... const renderItems = () => { let list = []; tasks.forEach((item, index) => { if ( (filter === "SHOW_ALL") || (filter === "SHOW_TODO" && !item.isCompleted) || (filter === "SHOW_DONE" && item.isCompleted) ) { list.push( <TaskItem key={item.taskName} task={{ ...item, idx: index }} /> ); } }); return list; }; return ( <Wrapper> ... <TaskItemContainer>{renderItems()}</TaskItemContainer> </Wrapper> ); } ``` ![](https://i.imgur.com/G8q91sj.gif) ## 勾選 Task 終於完成任務清單和篩選器的功能,剩下最後一個功能 — 完成任務的時候要可以勾選框框,設定任務的狀態。一樣在 ActionTypes.js 定義勾選任務的動作 TOGGLE_TASK。 actions/ActionTypes.js ```javascript= ... export const TOGGLE_TASK = 'TOGGLE_TASK'; ``` Step1:建立 Action Creator 產生勾選 Task 的動作 Function toggleTask,並取得對應的任務索引值。 actions/todos.js ```javascript= export function toggleTask(idx){ return { type: types.TOGGLE_TASK, idx }; } ``` Step2:處理 Todo Reducer,讀取 action.type 為 TOGGLE_TASK 時,修改該任務的完成狀態並回傳的新 State。 reducer/todos.js ```javascript= ... export default function todos(state = initialTasks, action) { switch (action.type) { case types.ADD_TASK:... case types.DELETE_TASK:... case types.TOGGLE_TASK: let newState = [...state]; newState[action.idx].isCompleted = !newState[action.idx].isCompleted; return newState; default:... } } ``` Step3:完成 Action 和 Reducer 的設定後,在 TaskItem Component 利用 ```useDispatch()``` 來調用 Action。點擊 ```<CheckBox />``` 後直接呼叫 ```toggleTask()```,傳入對應的任務索引值。 components/TaskItem.js ```jsx= function TaskItem(props) { const dispatch = useDispatch(); return ( <Container> <CheckBox type="checkbox" checked={...} onChange={() => dispatch(actions.toggleTask(props.task.idx))} /> ... </Container> ); } ``` *** ## 小結 ![](https://i.imgur.com/AVSwmgD.gif) >這樣就完成了一個簡單的 Todolist 囉 [範例程式碼](https://github.com/peiyunlee/ithome-21ironman-todolist)、[完成品](https://peiyunlee.github.io/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