關於react-redux中Provider、connect的解析

Provider

是什麼

react-redux 提供的一個 React 組件php

做用

把 store 提供給其子組件css

  1. //使用 redux 的 createStore 方法建立的一個 store
  2. const store = createStore(todoApp,{})
  3. // store 做爲一個 prop 傳給 Provider 組件
  4. render(
  5. <Provider store={store}>
  6. <App/>
  7. </Provider>, document.getElementById('app'))

connect

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

做用

把「指定的state & 指定的action」和 React組件 鏈接起來 ==> 容器組件html

參數說明

mapStateToProps

這是一個function,返回一個object;react

(state, [ownProps]) => ({ }) // 一般省略第二個參數apache

做用 把指定的state做爲props注入到 UI組件 中redux

  1. const mapStateToProps = state => {
  2. return {
  3. title: state.title
  4. list: state.list
  5. };
  6. }

固然,沒必要將 state 中的數據原封不動地傳入組件,能夠根據 state 中的數據,動態地輸出組件須要的(最小)屬性。markdown

  1. const mapStateToProps = (state) => {
  2. return {
  3. greaterThanFive: state.count > 5 // 假如只須要知道count大不大於5就成
  4. }
  5. }

函數的第二個參數 ownProps,是 React的UI組件本身的 props。有的時候,ownProps 也會對其產生影響。
好比,當你在 store 中維護了一個用戶列表,而你的組件只關心一個用戶。app

  1. const mapStateToProps = (state, ownProps) => {
  2. // state 是 {userList: [{id: 0, name: '王二'},{id: 1, name: '李四'}]}
  3. return {
  4. user: _.find(state.userList, {id: ownProps.userId})
  5. }
  6. }
  7. class MyComp extends Component {
  8. static PropTypes = {
  9. userId: PropTypes.string.isRequired,
  10. user: PropTypes.object
  11. };
  12. render(){
  13. return <div>用戶名:{this.props.user.name}</div>
  14. }
  15. }
  16. const Comp = connect(mapStateToProps)(MyComp);

mapDispatchToProps

這能夠是一個function,還能夠是object,less

做用 把指定的action做爲props注入到UI組件中ide

  1. // 方法
  2. const mapDispatchToProps = dispatch => {
  3. return {
  4. destroyTodo : () => dispatch({
  5. type : 'DESTROY_TODO'
  6. })
  7. }
  8. }
  9. // 對象

mergeProps

是一個函數,用來篩選哪些參數傳遞給組件。這個函數接受3個參數

  1. const defaultMergeProps = (stateProps, dispatchProps, ownProps ) => ({
  2. ...ownProps,
  3. ...stateProps,
  4. ...dispatchProps
  5. })

stateProps是mapStateToProps的返回值,dispatchProps是mapDispatchToProps返回值,ownProps 是當前組件本身的屬性。
這個函數默認把這三個返回值拼裝到一塊兒傳遞給組件,可修改。

options

一個對象,有兩個布爾,一個是pure,一個是withRef。

  • pure爲false,只要connect接受到屬性,無論是否有變化,必然刷新connect組件。
  • withRef爲true時,在裝飾傳入的 React 組件時,Connect 會保存一個對該組件的 refs 引用,能夠經過 getWrappedInstance 方法來得到該 refs,並最終得到原始的 DOM 節點。

使用

  1. const newApp = connect(store)(UI)
相關文章
相關標籤/搜索