這邊來自於:
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吧。
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。
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該去哪裡了。
今天文章也寫完了,
感謝大家!!