<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??碼云GVP開源項目 12k star Uniapp+ElementUI 功能強大 支持多語言、二開方便! 廣告
                前兩篇教程介紹了 Redux 的[基本用法](216731)和[異步操作](216732),今天是最后一部分,介紹如何在 React 項目中使用 Redux。 [TOC] 為了方便使用,Redux 的作者封裝了一個 React 專用的庫?[React-Redux](https://github.com/reactjs/react-redux),本文主要介紹它。 這個庫是可以選用的。實際項目中,你應該權衡一下,是直接使用 Redux,還是使用 React-Redux。后者雖然提供了便利,但是需要掌握額外的 API,并且要遵守它的組件拆分規范。 ![](http://www.ruanyifeng.com/blogimg/asset/2016/bg2016092101.jpg) ## 一、UI 組件 React-Redux 將所有組件分成兩大類:UI 組件(presentational component)和容器組件(container component)。 UI 組件有以下幾個特征。 > * 只負責 UI 的呈現,不帶有任何業務邏輯 > * 沒有狀態(即不使用`this.state`這個變量) > * 所有數據都由參數(`this.props`)提供 > * 不使用任何 Redux 的 API 下面就是一個 UI 組件的例子。 > ~~~ > const Title = > value => <h1>{value}</h1>; > ~~~ 因為不含有狀態,UI 組件又稱為"純組件",即它純函數一樣,純粹由參數決定它的值。 ## 二、容器組件 容器組件的特征恰恰相反。 > * 負責管理數據和業務邏輯,不負責 UI 的呈現 > * 帶有內部狀態 > * 使用 Redux 的 API 總之,只要記住一句話就可以了:UI 組件負責 UI 的呈現,容器組件負責管理數據和邏輯。 你可能會問,如果一個組件既有 UI 又有業務邏輯,那怎么辦?回答是,將它拆分成下面的結構:外面是一個容器組件,里面包了一個UI 組件。前者負責與外部的通信,將數據傳給后者,由后者渲染出視圖。 React-Redux 規定,所有的 UI 組件都由用戶提供,容器組件則是由 React-Redux 自動生成。也就是說,用戶負責視覺層,狀態管理則是全部交給它。 ## 三、connect() React-Redux 提供`connect`方法,用于從 UI 組件生成容器組件。`connect`的意思,就是將這兩種組件連起來。 > ~~~ > import { connect } from 'react-redux' > const VisibleTodoList = connect()(TodoList); > ~~~ 上面代碼中,`TodoList`是 UI 組件,`VisibleTodoList`就是由 React-Redux 通過`connect`方法自動生成的容器組件。 但是,因為沒有定義業務邏輯,上面這個容器組件毫無意義,只是 UI 組件的一個單純的包裝層。為了定義業務邏輯,需要給出下面兩方面的信息。 > (1)輸入邏輯:外部的數據(即`state`對象)如何轉換為 UI 組件的參數 > > (2)輸出邏輯:用戶發出的動作如何變為 Action 對象,從 UI 組件傳出去。 因此,`connect`方法的完整 API 如下。 > ~~~ > import { connect } from 'react-redux' > > const VisibleTodoList = connect( > mapStateToProps, > mapDispatchToProps > )(TodoList) > ~~~ 上面代碼中,`connect`方法接受兩個參數:`mapStateToProps`和`mapDispatchToProps`。它們定義了 UI 組件的業務邏輯。前者負責輸入邏輯,即將`state`映射到 UI 組件的參數(`props`),后者負責輸出邏輯,即將用戶對 UI 組件的操作映射成 Action。 ## 四、mapStateToProps() `mapStateToProps`是一個函數。它的作用就是像它的名字那樣,建立一個從(外部的)`state`對象到(UI 組件的)`props`對象的映射關系。 作為函數,`mapStateToProps`執行后應該返回一個對象,里面的每一個鍵值對就是一個映射。請看下面的例子。 > ~~~ > const mapStateToProps = (state) => { > return { > todos: getVisibleTodos(state.todos, state.visibilityFilter) > } > } > ~~~ 上面代碼中,`mapStateToProps`是一個函數,它接受`state`作為參數,返回一個對象。這個對象有一個`todos`屬性,代表 UI 組件的同名參數,后面的`getVisibleTodos`也是一個函數,可以從`state`算出?`todos`?的值。 下面就是`getVisibleTodos`的一個例子,用來算出`todos`。 > ~~~ > const getVisibleTodos = (todos, filter) => { > switch (filter) { > case 'SHOW_ALL': > return todos > case 'SHOW_COMPLETED': > return todos.filter(t => t.completed) > case 'SHOW_ACTIVE': > return todos.filter(t => !t.completed) > default: > throw new Error('Unknown filter: ' + filter) > } > } > ~~~ `mapStateToProps`會訂閱 Store,每當`state`更新的時候,就會自動執行,重新計算 UI 組件的參數,從而觸發 UI 組件的重新渲染。 `mapStateToProps`的第一個參數總是`state`對象,還可以使用第二個參數,代表容器組件的`props`對象。 > ~~~ > // 容器組件的代碼 > // <FilterLink filter="SHOW_ALL"> > // All > // </FilterLink> > > const mapStateToProps = (state, ownProps) => { > return { > active: ownProps.filter === state.visibilityFilter > } > } > ~~~ 使用`ownProps`作為參數后,如果容器組件的參數發生變化,也會引發 UI 組件重新渲染。 `connect`方法可以省略`mapStateToProps`參數,那樣的話,UI 組件就不會訂閱Store,就是說 Store 的更新不會引起 UI 組件的更新。 ## 五、mapDispatchToProps() `mapDispatchToProps`是`connect`函數的第二個參數,用來建立 UI 組件的參數到`store.dispatch`方法的映射。也就是說,它定義了哪些用戶的操作應該當作 Action,傳給 Store。它可以是一個函數,也可以是一個對象。 如果`mapDispatchToProps`是一個函數,會得到`dispatch`和`ownProps`(容器組件的`props`對象)兩個參數。 > ~~~ > const mapDispatchToProps = ( > dispatch, > ownProps > ) => { > return { > onClick: () => { > dispatch({ > type: 'SET_VISIBILITY_FILTER', > filter: ownProps.filter > }); > } > }; > } > ~~~ 從上面代碼可以看到,`mapDispatchToProps`作為函數,應該返回一個對象,該對象的每個鍵值對都是一個映射,定義了 UI 組件的參數怎樣發出 Action。 如果`mapDispatchToProps`是一個對象,它的每個鍵名也是對應 UI 組件的同名參數,鍵值應該是一個函數,會被當作 Action creator ,返回的 Action 會由 Redux 自動發出。舉例來說,上面的`mapDispatchToProps`寫成對象就是下面這樣。 > ~~~ > const mapDispatchToProps = { > onClick: (filter) => { > type: 'SET_VISIBILITY_FILTER', > filter: filter > }; > } > ~~~ ## 六、 組件 `connect`方法生成容器組件以后,需要讓容器組件拿到`state`對象,才能生成 UI 組件的參數。 一種解決方法是將`state`對象作為參數,傳入容器組件。但是,這樣做比較麻煩,尤其是容器組件可能在很深的層級,一級級將`state`傳下去就很麻煩。 React-Redux 提供`Provider`組件,可以讓容器組件拿到`state`。 > ~~~ > import { Provider } from 'react-redux' > import { createStore } from 'redux' > import todoApp from './reducers' > import App from './components/App' > > let store = createStore(todoApp); > > render( > <Provider store={store}> > <App /> > </Provider>, > document.getElementById('root') > ) > ~~~ 上面代碼中,`Provider`在根組件外面包了一層,這樣一來,`App`的所有子組件就默認都可以拿到`state`了。 它的原理是`React`組件的[`context`](https://facebook.github.io/react/docs/context.html)屬性,請看源碼。 > ~~~ > class Provider extends Component { > getChildContext() { > return { > store: this.props.store > }; > } > render() { > return this.props.children; > } > } > > Provider.childContextTypes = { > store: React.PropTypes.object > } > ~~~ 上面代碼中,`store`放在了上下文對象`context`上面。然后,子組件就可以從`context`拿到`store`,代碼大致如下。 > ~~~ > class VisibleTodoList extends Component { > componentDidMount() { > const { store } = this.context; > this.unsubscribe = store.subscribe(() => > this.forceUpdate() > ); > } > > render() { > const props = this.props; > const { store } = this.context; > const state = store.getState(); > // ... > } > } > > VisibleTodoList.contextTypes = { > store: React.PropTypes.object > } > ~~~ `React-Redux`自動生成的容器組件的代碼,就類似上面這樣,從而拿到`store`。 ## 七、實例:計數器 我們來看一個實例。下面是一個計數器組件,它是一個純的 UI 組件。 > ~~~ > class Counter extends Component { > render() { > const { value, onIncreaseClick } = this.props > return ( > <div> > <span>{value}</span> > <button onClick={onIncreaseClick}>Increase</button> > </div> > ) > } > } > ~~~ 上面代碼中,這個 UI 組件有兩個參數:`value`和`onIncreaseClick`。前者需要從`state`計算得到,后者需要向外發出 Action。 接著,定義`value`到`state`的映射,以及`onIncreaseClick`到`dispatch`的映射。 > ~~~ > function mapStateToProps(state) { > return { > value: state.count > } > } > > function mapDispatchToProps(dispatch) { > return { > onIncreaseClick: () => dispatch(increaseAction) > } > } > > // Action Creator > const increaseAction = { type: 'increase' } > ~~~ 然后,使用`connect`方法生成容器組件。 > ~~~ > const App = connect( > mapStateToProps, > mapDispatchToProps > )(Counter) > ~~~ 然后,定義這個組件的 Reducer。 > ~~~ > // Reducer > function counter(state = { count: 0 }, action) { > const count = state.count > switch (action.type) { > case 'increase': > return { count: count + 1 } > default: > return state > } > } > ~~~ 最后,生成`store`對象,并使用`Provider`在根組件外面包一層。 > ~~~ > import { loadState, saveState } from './localStorage'; > > const persistedState = loadState(); > const store = createStore( > todoApp, > persistedState > ); > > store.subscribe(throttle(() => { > saveState({ > todos: store.getState().todos, > }) > }, 1000)) > > ReactDOM.render( > <Provider store={store}> > <App /> > </Provider>, > document.getElementById('root') > ); > ~~~ 完整的代碼看[這里](https://github.com/jackielii/simplest-redux-example/blob/master/index.js)。 ## 八、React-Router 路由庫 使用`React-Router`的項目,與其他項目沒有不同之處,也是使用`Provider`在`Router`外面包一層,畢竟`Provider`的唯一功能就是傳入`store`對象。 > ~~~ > const Root = ({ store }) => ( > <Provider store={store}> > <Router> > <Route path="/" component={App} /> > </Router> > </Provider> > ); > ~~~ (完)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看