connect([mapStateToProps], [mapDispatchToProps], [mergeProps],[options])
連接 React 組件與 Redux store。
連接操作不會改變原來的組件類,反而返回一個新的已與 Redux store 連接的組件類。
參數
-
[
mapStateToProps(state, [ownProps]): stateProps
] (Function): 如果定義該參數,組件將會監聽 Redux store 的變化。任何時候,只要 Redux store 發生改變,mapStateToProps
函數就會被調用。該回調函數必須返回一個純對象,這個對象會與組件的 props 合並。如果你省略了這個參數,你的組件將不會監聽 Redux store。如果指定了該回調函數中的第二個參數ownProps
,則該參數的值為傳遞到組件的 props,而且只要組件接收到新的 props,mapStateToProps
也會被調用。 -
[
mapDispatchToProps(dispatch, [ownProps]): dispatchProps
] (Object or Function): 如果傳遞的是一個對象,那么每個定義在該對象的函數都將被當作 Redux action creator,而且這個對象會與 Redux store 綁定在一起,其中所定義的方法名將作為屬性名,合並到組件的 props 中。如果傳遞的是一個函數,該函數將接收一個dispatch
函數,然后由你來決定如何返回一個對象,這個對象通過dispatch
函數與 action creator 以某種方式綁定在一起(提示:你也許會用到 Redux 的輔助函數bindActionCreators()
)。如果你省略這個mapDispatchToProps
參數,默認情況下,dispatch
會注入到你的組件 props 中。如果指定了該回調函數中第二個參數ownProps
,該參數的值為傳遞到組件的 props,而且只要組件接收到新 props,mapDispatchToProps
也會被調用。 -
[
mergeProps(stateProps, dispatchProps, ownProps): props
] (Function): 如果指定了這個參數,mapStateToProps()
與mapDispatchToProps()
的執行結果和組件自身的props
將傳入到這個回調函數中。該回調函數返回的對象將作為 props 傳遞到被包裝的組件中。你也許可以用這個回調函數,根據組件的 props 來篩選部分的 state 數據,或者把 props 中的某個特定變量與 action creator 綁定在一起。如果你省略這個參數,默認情況下返回Object.assign({}, ownProps, stateProps, dispatchProps)
的結果。 -
[
options
] (Object) 如果指定這個參數,可以定制 connector 的行為。- [
pure = true
] (Boolean): 如果為 true,connector 將執行shouldComponentUpdate
並且淺對比mergeProps
的結果,避免不必要的更新,前提是當前組件是一個“純”組件,它不依賴於任何的輸入或 state 而只依賴於 props 和 Redux store 的 state。默認值為true
。 - [
withRef = false
] (Boolean): 如果為 true,connector 會保存一個對被包裝組件實例的引用,該引用通過getWrappedInstance()
方法獲得。默認值為false
- [
返回值
根據配置信息,返回一個注入了 state 和 action creator 的 React 組件。
靜態屬性
WrappedComponent
(Component): 傳遞到connect()
函數的原始組件類。
靜態方法
組件原來的靜態方法都被提升到被包裝的 React 組件。
實例方法
getWrappedInstance(): ReactComponent
僅當 connect()
函數的第四個參數 options
設置了 { withRef: true }
才返回被包裝的組件實例。
備注
-
函數將被調用兩次。第一次是設置參數,第二次是組件與 Redux store 連接:
connect(mapStateToProps, mapDispatchToProps, mergeProps)(MyComponent)
。 -
connect 函數不會修改傳入的 React 組件,返回的是一個新的已與 Redux store 連接的組件,而且你應該使用這個新組件。
-
mapStateToProps
函數接收整個 Redux store 的 state 作為 props,然后返回一個傳入到組件 props 的對象。該函數被稱之為 selector。參考使用 reselect 高效地組合多個 selector ,並對 收集到的數據進行處理。