react七——react-redux

react-redux

咱們知道redux是:store中維護了一個state,當咱們view層dispatch了一個action,而後reducer根據這個action來更新state。
而react-redux呢,是react和redux的一個橋樑,也不是說沒有他 react和redux不能使用,而是他作了一些封裝,使得開發者可以更方便的使用redux
react-redux將組件分紅兩種:
一、容器組件(智能組件):容器組件負責作數據交互
二、UI組件(木偶組件):UI組件嵌套在容器組件裏,只負責使用數據來顯示數據

比起redux新增 兩個模塊
一、Provider 組件來對Router進行包裹,並傳入store,這樣在內部組件的其餘組件均可以共享store的數據 而且對其進行更改javascript

在根組件中導入
     import {Provider} from 'react-redux'
     ...
     import store from './javascripts/redux/store'
     ReactDOM.render(
        <Provider store={store} >
            <Router history={hashHistory}>
                <Route path="/" component={App}>
                    <IndexRoute component={A}/>
                    <Route path="/a" component={A}></Route>
                    <Route path="/b" component={B}></Route>
                </Route>
            </Router>
        </Provider>
    ,document.getElementById("app"))

二、connect 是將store中的數據經過props來顯示在view層,並封裝一個函數來響應用戶操做時dispatch的actionjava

import {connect} from 'react-redux'
import Actions from './redux/actionCreator'
...
 const mapStateToProps = (state) => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter)
  }
}

const mapDispatchToProps = (
  dispatch,
  ownProps
) => {
  return {
    onClick: () => {
      dispatch({
        type: 'SET_VISIBILITY_FILTER',
        filter: ownProps.filter
      });
    }
  };
}

export default connect(mapStateToProps,mapDispatchToProps)(A)

view層: <div>{this.props. todos}</div>

解析: connect接受的兩個參數react

  • mapStateToPropsredux

    是對store裏的state和組件裏的props對象造成映射關係,
    每當store中的state有所更新,就會自動執行,從新計算,從而從新render
    固然,他能夠穿兩個參數(state,ownProps) 這裏若是容器組件裏的ownprops改變,也會重新渲染
    eg: 
       // 容器組件的代碼
           <FilterLink filter="SHOW_ALL">
             All
           </FilterLink>
       
       const mapStateToProps = (state, ownProps) => {
         return {
           active: ownProps.filter === state.visibilityFilter
         }
       }
    他能夠接收state參數,並返回一個對象,這樣你就能夠在這裏進行對數據的處理
    
    eg:
        const mapStateToProps = (state) => {
         return {
           todos: getVisibleTodos(state.todos, state.visibilityFilter)
         }
       }
  • mapDispatchToPropsapp

    這個函數或對象 是用來將用戶的action傳給store,他能夠是一個函數,也能夠是一個對象
       函數:
           const mapDispatchTopProps = (dispatch,ownProps) = > {
               return {
                   onClick: () => {
                       dispatch({
                           type: 'ADD_NUM',
                           filter:ownProps.filter
                       })
                   }
               }
           }
          這裏,做爲函數,他返回一個對象,對象裏的鍵值對定義了ui組件的參數怎麼發出action
      對象:
          const mapDispatchToProps = {
             onClick: (filter) => {
               type: 'ADD_NUM',
               filter: filter
             };
           }
           這裏,是將上面的函數寫成對象形式

    這一塊就寫到這裏,若是有新的感悟會加進來....ide

相關文章
相關標籤/搜索