iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 22
0
Modern Web

RRRR的世界 (Ruby on Rails + React + Redux)系列 第 22

Day 22, Redux - 先理解一下

RRRR的最後一個R,就像最後的戰役!

先上文件:

  1. 原文其實不難懂: http://redux.js.org/
  2. 中文Redux文檔: https://chentsulin.github.io/redux/
  3. 還有我剛剛看到的video: https://egghead.io/courses/getting-started-with-redux

那張圖應該到今年已經爛掉了,我就不要再PO那張圖好了。
基本上就是個循環:

reducer --> store --> react --> action --> reducer --> store... ... ...

有玩沒完?
有的!一定會停在react,"等"下一個action!!
(這次不是圖了,應該更好理解)

所以,看得很清楚,基本上就是三個東西

Action/ActionCreator

Action: 純Javascript Object,也就是{}包起來的東西,然後記得一定要有type給reducer去辨識
ActionCreator: 產生Action的function,也就是你可以傳入參數,然後這個function會回傳一個action,再把這個action dispatch出去!

搞混了嗎,我也常搞混這兩個字,雖然官方說不要輕易搞混:

An action creator is, quite simply, a function that creates an action. Do not confuse the two terms—again, an action is a payload of information, and an action creator is a factory that creates an action.

reducer

分類Action的type,哪個type要回傳怎樣的state,我喜歡看下面這段強烈的建議:

It's very important that the reducer stays pure. Things you should never do inside a reducer:

  1. Mutate its arguments;
  2. Perform side effects like API calls and routing transitions;
  3. Call non-pure functions, e.g. Date.now() or Math.random().

We'll explore how to perform side effects in the advanced walkthrough. For now, just remember that the reducer must be pure. Given the same arguments, it should calculate the next state and return it. No surprises. No side effects. No API calls. No mutations. Just a calculation.

他也很單純,不用定義或搞懂太多,一個大原則,輸入舊的state跟action,輸出一個全新的state
(previousState, action) => newState

store

基本上只有一個,除非你有以下考量:

  • 因為不斷update state造成的Performance issue
  • 確定你有很多個Redux App的話,一個root redux app可以用一個store,不然的話你應該用很多Reducer去包起來

(不負責任翻譯原文:http://redux.js.org/docs/faq/StoreSetup.html)

你只有一個store還有一個好處,就是你可以使用Redex-devtool去debug你的action有沒有回傳正確的state。

另外,大部分的state也會藏在store裡面,你絕對不能隨便改變他(使用setState 或 this.state=xxx),應該是用reducer去回傳新的state,剩下的讓包在store裡面的code去處理。
當然你也可以試試看會發生什麼事情,如果有問題記得先回頭看看是不是哪裡改到了state!

最後講到Data Flow

就是4個steps:

  1. 呼叫store.dispatch(actioin)
  2. redux呼叫我們定義好的reducer function
  3. reducer 回傳一個state (會包含所有你定義的reducer的state or default state)
  4. store存下reducer產生的新state,剩下就讓你的component去發揮/更新了!

今天整理文章比較快,準時上傳。
明天開始會慢慢拆分,慢慢把該定義成action的定義出來、reducer寫好、store建好。
OK,打完收工
(我要去看最火紅的RxJS系列文章了)


上一篇
Day 21, Reading List - React部分-3
下一篇
Day 23, Redux 一樣先玩範例!
系列文
RRRR的世界 (Ruby on Rails + React + Redux)30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言