react-router搭配react-redux沒法監聽路由變化的問題

在react中,要將react組件鏈接到redux中,一般會這樣包裝組件html

class Home extends Component {

}

function select(state) {
  return {
    logBox:state.logBox
  }
}

export default connect(select)(Home)

可是當搭配react-router的時候,在進行路由跳轉的時候,組件不會從新render。這個時候看react-redux的connect方法的說明:react

connect([mapStateToProps][mapDispatchToProps][mergeProps],[options])

mapStateToProps(state[ownProps]):若是定義該參數,組件將會監聽 Redux store 的變化。git

mapDispatchToProps(dispatch[ownProps]):若是傳遞的是一個對象,那麼每一個定義在該對象的函數都將被看成 Redux action creator,並且這個對象會與 Redux store 綁定在一塊兒,其中所定義的方法名將做爲屬性名,合併到組件的 props 中。若是傳遞的是一個函數,該函數將接收一個 dispatch 函數,而後由你來決定如何返回一個對象,這個對象經過 dispatch 函數與 action creator 以某種方式綁定在一塊兒(提示:你也許會用到 Redux 的輔助函數 bindActionCreators()github

mergeProps(stateProps, dispatchProps, ownProps):若是指定了這個參數,mapStateToProps() 與 mapDispatchToProps() 的執行結果和組件自身的 props 將傳入到這個回調函數中。該回調函數返回的對象將做爲 props 傳遞到被包裝的組件中。redux

options:api

若是指定這個參數,能夠定製 connector 的行爲。react-router

  • [pure true(Boolean): 若是爲 true,connector 將執行 shouldComponentUpdate 而且淺對比 mergeProps 的結果,避免沒必要要的更新,前提是當前組件是一個「純」組件,它不依賴於任何的輸入或 state 而只依賴於 props 和 Redux store 的 state。默認值爲 true
  • [withRef false(Boolean): 若是爲 true,connector 會保存一個對被包裝組件實例的引用,該引用經過 getWrappedInstance() 方法得到。默認值爲 false

options中pure屬性默認爲true,估計是由於淺對比的緣由,沒有獲取到路由的變化,所以能夠將pure設置爲falseapp

class Home extends Component {

}

function select(state) {
  return {
    logBox:state.logBox
  }
}

export default connect(select,undefined,undefined,{pure:false})(Home)

這樣路由變化的時候,該組件就能監聽而且從新render了。函數

相關文章
相關標籤/搜索