在react中,要將react組件連接到redux中,通常會這樣包裝組件
class Home extends Component { } function select(state) { return { logBox:state.logBox } } export default connect(select)(Home)
但是當搭配react-router的時候,在進行路由跳轉的時候,組件不會重新render。這個時候看react-redux的connect方法的說明:
connect([mapStateToProps], [mapDispatchToProps], [mergeProps],[options])
mapStateToProps(state, [ownProps]):如果定義該參數,組件將會監聽 Redux store 的變化。
mapDispatchToProps(dispatch, [ownProps]):如果傳遞的是一個對象,那么每個定義在該對象的函數都將被當作 Redux action creator,而且這個對象會與 Redux store 綁定在一起,其中所定義的方法名將作為屬性名,合並到組件的 props 中。如果傳遞的是一個函數,該函數將接收一個 dispatch
函數,然后由你來決定如何返回一個對象,這個對象通過 dispatch
函數與 action creator 以某種方式綁定在一起(提示:你也許會用到 Redux 的輔助函數 bindActionCreators()
)
mergeProps(stateProps, dispatchProps, ownProps):如果指定了這個參數,mapStateToProps()
與 mapDispatchToProps()
的執行結果和組件自身的 props
將傳入到這個回調函數中。該回調函數返回的對象將作為 props 傳遞到被包裝的組件中。
options:
如果指定這個參數,可以定制 connector 的行為。
- [
pure = true
] (Boolean): 如果為 true,connector 將執行shouldComponentUpdate
並且淺對比mergeProps
的結果,避免不必要的更新,前提是當前組件是一個“純”組件,它不依賴於任何的輸入或 state 而只依賴於 props 和 Redux store 的 state。默認值為true
。 - [
withRef = false
] (Boolean): 如果為 true,connector 會保存一個對被包裝組件實例的引用,該引用通過getWrappedInstance()
方法獲得。默認值為false
options中pure屬性默認為true,估計是因為淺對比的原因,沒有獲取到路由的變化,因此可以將pure設置為false
class Home extends Component { } function select(state) { return { logBox:state.logBox } } export default connect(select,undefined,undefined,{pure:false})(Home)
這樣路由變化的時候,該組件就能監聽並且重新render了。