簡(jiǎn)介
React Redux框架可以用來(lái)對(duì)React Native進(jìn)行數(shù)據(jù)流管理。Redux是一個(gè)用于UI布局框架的標(biāo)準(zhǔn)庫(kù)。Redux的概念是通過(guò)UI binding來(lái)將Redux和React綁定到一起,這樣可以避免UI 部分和store直接交互。
UI binding
從組件布局來(lái)講,當(dāng)我們?cè)跇?gòu)建一個(gè)大型組件,且內(nèi)部每個(gè)小模塊分工不同時(shí),合理的設(shè)計(jì)方式是將各個(gè)部分按照功能進(jìn)行拆分,在外部提供一個(gè)公共“容器”,用于處理數(shù)據(jù),展示層只負(fù)責(zé)顯示接收到的參數(shù)。
而Redux的connect函數(shù)就是提供了這種容器功能,用于管理數(shù)據(jù),我們的React組件只需要接收和顯示參數(shù)即可。
使用手冊(cè)
React Redux有幾個(gè)基本概念:Store、Action、connect。
React Redux結(jié)構(gòu)圖:

使用action而不是直接編寫(xiě)function的優(yōu)點(diǎn)在于,組件只需要告知外部需要做什么,只關(guān)心如何觸發(fā)動(dòng)作,而不必關(guān)心觸發(fā)了什么動(dòng)作。
Store
Store是用來(lái)維持所有state樹(shù)的一個(gè)對(duì)象,一個(gè)項(xiàng)目只有一個(gè)單一的store。Redux使用單向數(shù)據(jù)流的管理方式,改變store內(nèi)state的唯一途徑是對(duì)它dispatch一個(gè)action。
通過(guò)<Provider />來(lái)包裹項(xiàng)目布局。
import App from './App'
import { Provider } from 'react-redux'
import store from './redux/store'
...
render(
<Provider store={store}>
<App />
</Provider>
...
)
Connect
connect是Redux提供的用于讀取store內(nèi)數(shù)據(jù)的函數(shù),并且在store更新時(shí)獲取最新的數(shù)據(jù)。
connect具有以下功能:
- 自動(dòng)處理對(duì)store的訂閱,可以進(jìn)行方法分派。
- 渲染時(shí)機(jī)優(yōu)化:自動(dòng)實(shí)現(xiàn)了
shouldComponentUpdate,并且只會(huì)在訂閱的信息更新時(shí)才出發(fā)re-render。 - 隔絕了數(shù)據(jù)訂閱者和store直接的不必要聯(lián)系,組件不需要關(guān)心store的細(xì)節(jié),只需知道自己訂閱的數(shù)據(jù)格式即可。
- connect會(huì)將訂閱的數(shù)據(jù)和需要派發(fā)的函數(shù),以props的形式注入到組件中。
connect函數(shù)提供了兩個(gè)可選參數(shù):
-
mapStateToProps:每次state變化時(shí)都會(huì)被調(diào)用,接受全局state,需要返回當(dāng)前組件需要的數(shù)據(jù)。 -
mapDispatchToProps:該參數(shù)可以是函數(shù)或者對(duì)象。- 函數(shù)。只在組件創(chuàng)建時(shí)調(diào)用,接收
dispatch作為參數(shù),返回一個(gè)包含一個(gè)或多個(gè)參數(shù)的對(duì)象,用于使用dispatch來(lái)分派action。 - 對(duì)象。包含多個(gè)action創(chuàng)建器的對(duì)象。每個(gè)action都會(huì)轉(zhuǎn)換成自動(dòng)分派的函數(shù)。
示例代碼如下:
- 函數(shù)。只在組件創(chuàng)建時(shí)調(diào)用,接收
const mapStateToProps = (state, ownProps) => ({
// ... computed data from state and optionally ownProps
})
const mapDispatchToProps = {
// ... normally is an object full of action creators
}
// `connect` returns a new function that accepts the component to wrap, and that function returns the connected, wrapper component, We normally do both in one step, like this:
connect(
mapStateToProps,
mapDispatchToProps
)(Component)
組件connect之后,所連接的action會(huì)以Propsd的方式添加到組件內(nèi)。調(diào)用方式與屬性內(nèi)聲明的一直,可以使用() => { func() }或者this.props.func()的方式來(lái)調(diào)用。
參考資料
- React Redux Official Docs
- Store in Redux
- Action in Redux
- the Redux docs page on Computing Derived Data
- Idiomatic Redux: Using Reselect Selectors for Encapsulation and Performance
- Using the React Redux Bindings
- Higher Order Components in Depth
- Redux docs: Motivation
- Redux docs: FAQ - When should I use Redux?
- You Might Not Need Redux
- Idiomatic Redux: The Tao of Redux, Part 1 - Implementation and Intent