iT邦幫忙

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

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

Day 28, State in Redux or React? 搞混了嗎~

這邊來自於:

  1. Redux Github討論串: https://github.com/reactjs/redux/issues/1287#issuecomment-175351978
  2. Redux 官方FAQ: http://redux.js.org/docs/faq/OrganizingState.html#organizing-state-only-redux-state

首先,先看看@gaearon的說法,來分類state:

Use React for ephemeral state that doesn't matter to the app globally and doesn't mutate in complex ways. For example, a toggle in some UI element, a form input state
Use Redux for state that matters globally or is mutated in complex ways. For example, cached users, or a post draft.

讓那些短暫的狀態留在react裡,像是對UI的操作跟input的變化,他們既不用被整個APP知道,也不會有複雜的改變。讓其他要被Global知道的或會有複雜操作的狀態,放在Redux。
需要被Global知道的狀態,是不是馬上聯想到this.context?就把它們搬去redux吧。

接著@xogeny分類出一些名詞:

UI state is that I think of as ephemeral.
Application state is really the persistent core of the application
routing state, I abstract this to a "view selection" state

分出了短暫的UI state、APP需要用到的State,和跟routing有關的state。

除此之外,還有@inetfuture提到的重複使用上的分類

for non-reusable container, which has connection to Redux, just put everything into Redux store, even tiny UI state like if a modal is open, don't use this.setState any more.
for reusable component, which has nothing to do with Redux, use React state.

這樣分類也跟上面不衝突,像是route component、container/page component,他們要用到的state跑去redux;會重複使用的component要用到的state留在react。

最後 看官方的結論

Some common rules of thumb for determing what kind of data should be put into Redux:

  • Do other parts of the application care about this data?
  • Do you need to be able to create further derived data based on this original data?
  • Is the same data being used to drive multiple components?
  • Is there value to you in being able to restore this state to a given point in time (ie, time travel debugging)?
  • Do you want to cache the data (ie, use what's in state if it's already there instead of re-requesting it)?

如果以上有一個是YES,就搬到Redux吧!

我的總結

說實在的,放在哪裡也沒有對跟錯,但既然用了Redux,就用用它的原則:Single state tree。
然後討論串裡面也有講到,盡量不要讓你操控state操控的很awkward,要放哪裡的前提是"可以簡化它"。
再加上上面5點判斷,就很容易判斷你的state該去哪裡了。

今天文章也寫完了,
感謝大家!!


上一篇
Day 27, Example: Reading List
下一篇
Day 29, Deploy上heroku吧!
系列文
RRRR的世界 (Ruby on Rails + React + Redux)30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言