最近同學剛入手 react,問我像是 localstorage 的操作該寫在哪裡,我這邊就直接給一些建議

不管放哪,一定不會是 reducer

讓我來帶大家導讀一下 Redux 文件,請看Rules of Reducers的介紹:
We said earlier that reducers must always follow some special rules:

  • They should only calculate the new state value based on the state and action arguments
  • They are not allowed to modify the existing state. Instead, they must make immutable updates, by copying the existing state and making changes to the copied values.
  • They must not do any asynchronous logic or other “side effects”

Any function that follows these rules is also known as a “pure” function, even if it’s not specifically written as a reducer function.

reducer 應該保持 pure function 原則,透過 redux flow 從進入點到 store change
如果你從 reducer 直接使用 web API 的 localstorage,function 就不是 pure 了,而且也違反了 redux 的設計原則
在 reducer,頂多是把資料整理成特定的格式存在 store,不應該做額外的事情。
也許你會覺得不直接寫在 reducer 上很麻煩,但是如果後續開發有大量的程式跟著這樣做,就會變得更麻煩。

寫在 component 上

你可以寫在 useEffect 裏面,在特定的時機使用 localstorage,再把資料丟給 action 去跑 redux flow 更新 Store。

如果放 action 呢

來看一下文件:
Actions are plain JavaScript objects that have a type field. As mentioned earlier, you can think of an action as an event that describes something that happened in the application.

action 是一個 plain JavaScript objects,所以 component 呼叫 action 的時候,action 會把包含事件的 object 丟給 reducer 去做處理。

寫在 action 雖然也是很奇怪的一件事情,可是只要保持回傳的是 redux 能夠接受的格式即可。


Comment