為什麼用 Redux? / Why use Redux?

在 React 中,每個 Stateless Component 都必須保持 Pure,意思就是 Input 一樣的 prop 值,呈現出來的 UI 就會是一樣的,這樣的 Component 維護簡單也容易測試。持有 State 的叫做 Smart Component(以下稱 Container),它的任務就是將持有的 State 分派給所有的 Stateless Component。

當專案的規模一大,Container 的數量多,最常碰到的問題就是多個 Container 會需要用到同樣的 State,典型的解法就是 Container 再往上移一層,但久而久之重構次數多,維護成本相對也就高。

Redux 就是處理這樣的問題,將所有的 State 存在 Component 堆疊中的最上層 Store,根據各個 Component 的需要切出資料並往下傳遞,這樣一來 Store 以下的 Component 就幾乎都可以做到 Stateless 了。(當然大多數情況下還是需要 Container 持有 UI State)

In React, every stateless component should be pure, that means input the same prop value, it’ll always return the same UI representation, and this kind of component is simple and easy to test. Component which contain state called smart component(a.k.a. container), it’ll distribute the state to all stateless component.

What if the scale of project become large, the most common problem is that containers needs to use the same state, the typical solution is to move container up the hierarchy, but the cost will rise as long as keep doing this.

Redux is to solve this problem, store keep all state on the top of hierarchy, and seperate state to each components based on its requirement. Therefore, every other downstream components could be stateless (although in most cases, you still need container to hold UI state).

Reference

Like what you read? Give tonypai a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.