iT邦幫忙

2

React 學習筆記_26(在React中使用Redux - 2)

簡介

上一篇中提到了React與Redux的結合並且設計了Component的階層,本篇將照著設計好的Component進行實作。

Action Creater

建立產生Action的Function,包含 :

  • 加入新Todo的Action
  • 設定篩選Filter的Action
  • 指定id Todo 的Action
let nextTodoId = 0;

//新增Todo的Action
export const addTodo = (text) => {
    return{
        type : "ADD_TODO",
        id : nextTodoId++,
        text
    }
};

//設定篩選Filter的Aciton
export const setVisibilityFilter = (filter) => {
    return {
      type: 'SET_VISIBILITY_FILTER',
      filter
    }
};

//指定id Todo 的Action
export const toggleTodo = (id) => {
    return {
      type: 'TOGGLE_TODO',
      id
    }
};

Reducer

建立處理Action的Reducer,包含 :

  • 處理Todos的Reducer

    • 新增新的Todo物件
    • 改變指定Todo的Completed狀態
  • 處理visibilityFilter的Reducer

    • 改變篩選的Filter
import { combineReducers } from 'redux'

//將Reducer拆分
const todo = (state = {}, action) => {
    switch (action.type) {
      case 'ADD_TODO':
        return {
          id: action.id,
          text: action.text,
          completed: false
        }
      case 'TOGGLE_TODO':
        if (state.id !== action.id) {
          return state
        }
  
        return Object.assign({}, state, {
          completed: !state.completed
        })
  
      default:
        return state
    }
}
  
  const todos = (state = [], action) => {
    switch (action.type) {

      //呼叫todo function,新增新的todo到原本的Todos Array中 
      case 'ADD_TODO':
        return [
          ...state,
          todo(undefined, action)
        ]

      //改變指定todo狀態
      case 'TOGGLE_TODO':
        return state.map(t =>
          todo(t, action)
        )
      default:
        return state
    }
}

  const visibilityFilter = (state = 'SHOW_ALL', action) => {
    switch (action.type) {
      case 'SET_VISIBILITY_FILTER':
        return action.filter
      default:
        return state
    }
}

//透過Redux的utility 將兩個Reducer function結合為一個可以傳遞給createStore的單一reducers function
export const todoApp  = combineReducers({
    todos,
    visibilityFilter
})

index.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { createStore } from "redux";
import { Provider } from "react-redux";
import todoApp from "./Store/Reducers"

let store = createStore(todoApp);

//透過getState觀察目前state狀態
console.log(store.getState())

ReactDOM.render(
    <Provider store = {store}>
        <App />
    </Provider>,
    document.getElementById("root")
);

https://ithelp.ithome.com.tw/upload/images/20200516/20124767Jxg4MMLo0m.png

參考資料 :
從Redux 的作者學習它


尚未有邦友留言

立即登入留言