react-redux

簡介

react-redux 其實就是提供一個組件,整個 app 經過 connect 方法連接組件和 redux storereact

store 即爲整個 app 的 state 倉庫 根組件應該嵌套在中才能使用 connect 方法redux

connect(mapStateToProps, mapDispatchToProps, mergeProps, options)(Component)

此方法調用兩次,第一次是設置參數,第二次是將組件與 redux store 連接markdown

mapStateToProps(state, ownProps): stateProps (Function)

state 表示 redux store 中的存值 ownProps 表示該組件接收的值 此組件即爲 ownProps.value example:app

const mapStateToProps = state =>{
  return {
    someVal: state.someVal
  }
}
複製代碼

1.若是定義該參數,組件將會監聽 redux store 的變化,只有 store 發生變化,mapStateToProps 函數就會被調用 2.若是省略這個參數,組件相應的也不會監聽 store 的變化 3.該函數必須返回一個純對象,該對象會與當前組件的 props 合併 4.若是定義 ownProps,只要組件接收新的 props,mapStateToProps 函數就會被調用函數

mapDispatchToProps(dispatch, ownProps): dispatchProps (Object or Function)

example:oop

const mapDispatchToProps = {
  someAction
}
複製代碼

or:spa

const mapDispatchToProps = dispatch => {
  return {
    someFunction: (someArguments) => {
      dispatch(someAction(someArguments))
    }
  }
}
複製代碼

1.若是是一個 Object,那麼 obj 中的每一個值,都會被看成 action 中的方法 2.若是是一個 Function,接收一個 dispatch,返回一個對象 3.若是忽略此參數,默認 dispatch 會注入到當前組件 props 中 4.若是定義 ownProps,同 mapStateToPropscode

mergeProps(stateProps, dispatchProps, ownProps): props (Function)

example:orm

const mergeProps = (stateProps, dispatchProps, ownProps) => {
  return Object.assign({}, ownProps, {someProps: someMethodFilterState})
}
複製代碼

其實就是合併各類 state,dispatch 到 props 中 1。若是指定該參數,mapStateToProps,mapDispatchToProps 的執行結果和當前組件自身的 props 將傳入到此回調函數中,該回調函數返回的對象將做爲 props 傳到該組件中對象

options (Object)

pure = true default true 若是當前組件不依賴於任何的輸入而只依賴於 props 和 redux store 中的 state,即純組件,那麼將會執行 shouldComponentUpdate,淺對比 mergeProps 的結果,避免沒必要要的更新 withRef = false default false 若是爲 true,會保存一個當前組件實例的引用,該引用經過 getWrappedInstance()方法得到

參考連接: React Redux

相關文章
相關標籤/搜索