Redux

DMoon

國立彰化師範大學 資工系

創科資訊實習生

Blog

Github

Email: dmoon.t@gmail.com

Why we need Redux ?

剛學 React 的時候

用在專案上之後

  • react component 的 state 是獨立的

  • 無法直接修改其他 component 的 state

Redux

Design Pattern

Dealing with data

共用 State

集中管理

Predicable

Redux

Predictable State container
( evolution of Flux )

  • Single source of truth
     

  • State is read-only   ( Immutability )
     

  • Changes are made with pure functions

View
( React )

Store

Action

Reducer

dispatch

畫面需要改變

return

newState

資料變更

Server

Store

object tree

Immutable State

{
  todos: [
    {
      text: 'todo1',
      completed: true,
    },
  ],
}

Actions

Apply

const ADD_TODO = 'ADD_TODO';

// action
{
  type: ADD_TODO,
  text: 'Build my first Redux app',
}

// action creator
function requestAddTodo() {
  return {
    type: ADD_TODO,
    text: 'Build my first Redux app',
  };
}

Actions

Reducers

Return New State

newState.todos === prevState.todos

function todos(state = [], action) {
  switch (action.type) {
    case ADD_TODO:
      return [...state, {
        text: action.text,
        completed: false
      }];
    default:
      return state;
  }
}

Reducer

store = {
  todos: [{
    text: 'todo1 title',
    completed: false,
  },{
    text: 'todo2 title',
    completed: true,
  }],
}

{ conbineReducers } = redux

Persistent Data Structure

Time Travelling Debugger

Smart Component
v.s
Dumb Component

容器組件 展示組件
Location 最頂層,路由處理 中間和子組件
Aware of Redux
讀取數據 從 Redux 獲取 state 從 props 獲取數據
修改數據 向 Redux 派發 actions 從 props 調用回調函數

Smart

Dumb

Redux Tools

Dan Abramov

Redux Tools

Reference

Made with Slides.com