iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 18
2
Modern Web

React 30天系列 第 18

Day 18-回顧Redux

  • 分享至 

  • twitterImage
  •  

前情提要:
昨天很粗略地講了redux-promise怎麼用,走到middleware後也該跟redux告別了,最後的最後再讓我記錄一下Presentational和Container Components吧!

欸?不是要回顧了?回顧之前再看看使用redux後component可以怎麼劃分吧

Presentational and Container Components

在使用redux幫助我們管理狀態後,我們可以再把component細分拆成presentational componentscontainer components,它可讓我們的component更容易重複使用和理解,下面表格紀錄一下兩邊的差異。如過對於這個概念還不是很了解的話,可以左轉拜讀redux作者Dan Abramov所寫的Presentational and Container Components

  Presentational Components Container Components
目的 畫面長怎樣?(markup, styles) 事情怎麼運作?(data fetching, state updates)
Aware of Redux 沒有 是的
讀取資料方式 資料從props來 訂閱Redux state
改變資料方式 從props調用callback Dispatch Redux actions
寫入方式 手動處理 通常由react redux產生

好的,大致上區分法就是需要用到redux的component和不需要用到redux的component
這樣做有什麼好處呢?

  1. 分離關注點。可以更容易的把畫面跟邏輯拆開。
  2. 更好的可複用性。跟第一點相關,把畫面拆開後,presentational component就能夠根據不同資料來源顯示不同內容。
  3. 當設計師在調整畫面的時候不用碰到邏輯部分。
  4. 強制我們把"layout components"拆開,如Sidebar、Page、ContextMenu和使用this.props.children, 而不是在多個重複container components使用相同的markup和layout。

回顧Redux

  • store: 大腦擔當,協調Redux內所有moving parts
  • createStore: 一個function來建立Redux store,內部的參數為reducer
  • reducer: 產生application的state。本體為function,內含2個參數(state和action),依據action type來計算新的state,當沒有對應的action type時會回傳initial state。
  • combineReducers: 管理多個reducer。
  • action: 改變state的唯一方法是向store發送信號,那個信號就是action。"Dispatching an action"就是發送信號的過程。
  • middleware: 在dispatch action到action抵達reducer的過程間提供一個第三方的擴充點。我們可以使用 Redux middleware來記錄log、當機回報、與非同步API溝通、routing和其它功能。

回顧react-redux

  • Provider: 把整個React apllication包起來,讓裡面的component可以取得store的state
  • connect: 將React component和Redux store連結接起來為High Order Component(HOC)。
  • mapStateToProps : 它將部分的Redux state連接到React component的props,這樣React component就可以讀取它所需的state了。
  • mapDispatchToProps: 它也和樓上做了類似的事,但是是對action,它連結Redux action和React component的props,這樣就可以調用action了。

本日結束
明天開始react-router


上一篇
Day 17-redux middleware(使用redux-promise處理非同步資料吧)
下一篇
Day 19-你好,React Router 4(安裝及角色介紹)
系列文
React 30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言