React項目中使用Redux的?react-redux
背景
在前面文章一文理解Redux及其工作原理中,我們了解到redux
是用于數(shù)據(jù)狀態(tài)管理,而react
是一個視圖層面的庫
如果將兩者連接在一起,可以使用官方推薦react-redux
庫,其具有高效且靈活的特性
react-redux
將組件分成:
- 容器組件:存在邏輯處理
- UI 組件:只負(fù)責(zé)現(xiàn)顯示和交互,內(nèi)部不處理邏輯,狀態(tài)由外部控制
通過redux
將整個應(yīng)用狀態(tài)存儲到store
中,組件可以派發(fā)dispatch
行為action
給store
其他組件通過訂閱store
中的狀態(tài)state
來更新自身的視圖
UI 組件
React-Redux 將所有組件分成兩大類:UI 組件(presentational component)和容器組件(container component)。
UI 組件有以下幾個特征:
- 只負(fù)責(zé) UI 的呈現(xiàn),不帶有任何業(yè)務(wù)邏輯
- 沒有狀態(tài)(即不使用this.state這個變量)
- 所有數(shù)據(jù)都由參數(shù)(this.props)提供
- 不使用任何 Redux 的 API
下面就是一個 UI 組件的例子:
const Title = ? value => <h1>{value}</h1>;
因為不含有狀態(tài),UI 組件又稱為"純組件",即它純函數(shù)一樣,純粹由參數(shù)決定它的值。
容器組件
容器組件的特征恰恰相反。
- 負(fù)責(zé)管理數(shù)據(jù)和業(yè)務(wù)邏輯,不負(fù)責(zé) UI 的呈現(xiàn)
- 帶有內(nèi)部狀態(tài)
- 使用 Redux 的 API
總之,只要記住一句話就可以了:UI 組件負(fù)責(zé) UI 的呈現(xiàn),容器組件負(fù)責(zé)管理數(shù)據(jù)和邏輯。
你可能會問,如果一個組件既有 UI 又有業(yè)務(wù)邏輯,那怎么辦?回答是,將它拆分成下面的結(jié)構(gòu):外面是一個容器組件,里面包了一個UI 組件。前者負(fù)責(zé)與外部的通信,將數(shù)據(jù)傳給后者,由后者渲染出視圖。
React-Redux 規(guī)定,所有的 UI 組件都由用戶提供,容器組件則是由 React-Redux 自動生成。也就是說,用戶負(fù)責(zé)視覺層,狀態(tài)管理則是全部交給它。
connect()
React-Redux 提供connect方法,用于從 UI 組件生成容器組件。connect的意思,就是將這兩種組件連起來。
上面代碼中,TodoList是 UI 組件,VisibleTodoList就是由 React-Redux 通過connect方法自動生成的容器組件。
但是,因為沒有定義業(yè)務(wù)邏輯,上面這個容器組件毫無意義,只是 UI 組件的一個單純的包裝層。為了定義業(yè)務(wù)邏輯,需要給出下面兩方面的信息。
- 輸入邏輯:外部的數(shù)據(jù)(即state對象)如何轉(zhuǎn)換為 UI 組件的參數(shù)
- 輸出邏輯:用戶發(fā)出的動作如何變?yōu)?Action 對象,從 UI 組件傳出去。
import { connect } from 'react-redux' const VisibleTodoList = connect( ? mapStateToProps, ? mapDispatchToProps )(TodoList)
上面代碼中,connect方法接受兩個參數(shù):mapStateToProps和mapDispatchToProps。它們定義了 UI 組件的業(yè)務(wù)邏輯。前者負(fù)責(zé)輸入邏輯,即將state映射到 UI 組件的參數(shù)(props),后者負(fù)責(zé)輸出邏輯,即將用戶對 UI 組件的操作映射成 Action。
mapStateToProps()
mapStateToProps是一個函數(shù)。它的作用就是像它的名字那樣,建立一個從(外部的)state對象到(UI 組件的)props對象的映射關(guān)系。
作為函數(shù),mapStateToProps執(zhí)行后應(yīng)該返回一個對象,里面的每一個鍵值對就是一個映射。請看下面的例子。
const mapStateToProps = (state) => { ? return { ? ? todos: getVisibleTodos(state.todos, state.visibilityFilter) ? } }
上面代碼中,mapStateToProps是一個函數(shù),它接受state作為參數(shù),返回一個對象。這個對象有一個todos屬性,代表 UI 組件的同名參數(shù),后面的getVisibleTodos也是一個函數(shù),可以從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,每當(dāng)state更新的時候,就會自動執(zhí)行,重新計算 UI 組件的參數(shù),從而觸發(fā) UI 組件的重新渲染。
mapStateToProps的第一個參數(shù)總是state對象,還可以使用第二個參數(shù),代表容器組件的props對象。
// 容器組件的代碼 // ? ?<FilterLink filter="SHOW_ALL"> // ? ? ?All // ? ?</FilterLink> const mapStateToProps = (state, ownProps) => { ? return { ? ? active: ownProps.filter === state.visibilityFilter ? } }
使用ownProps作為參數(shù)后,如果容器組件的參數(shù)發(fā)生變化,也會引發(fā) UI 組件重新渲染。
connect方法可以省略mapStateToProps參數(shù),那樣的話,UI 組件就不會訂閱Store,就是說 Store 的更新不會引起 UI 組件的更新。
mapDispatchToProps()
mapDispatchToProps是connect函數(shù)的第二個參數(shù),用來建立 UI 組件的參數(shù)到store.dispatch方法的映射。也就是說,它定義了哪些用戶的操作應(yīng)該當(dāng)作 Action,傳給 Store。它可以是一個函數(shù),也可以是一個對象。
如果mapDispatchToProps是一個函數(shù),會得到dispatch和ownProps(容器組件的props對象)兩個參數(shù)。
const mapDispatchToProps = ( ? dispatch, ? ownProps ) => { ? return { ? ? onClick: () => { ? ? ? dispatch({ ? ? ? ? type: 'SET_VISIBILITY_FILTER', ? ? ? ? filter: ownProps.filter ? ? ? }); ? ? } ? }; }
從上面代碼可以看到,mapDispatchToProps作為函數(shù),應(yīng)該返回一個對象,該對象的每個鍵值對都是一個映射,定義了 UI 組件的參數(shù)怎樣發(fā)出 Action。
如果mapDispatchToProps是一個對象,它的每個鍵名也是對應(yīng) UI 組件的同名參數(shù),鍵值應(yīng)該是一個函數(shù),會被當(dāng)作 Action creator ,返回的 Action 會由 Redux 自動發(fā)出。舉例來說,上面的mapDispatchToProps寫成對象就是下面這樣。
const mapDispatchToProps = { ? onClick: (filter) => { ? ? type: 'SET_VISIBILITY_FILTER', ? ? filter: filter ? }; }
組件
connect方法生成容器組件以后,需要讓容器組件拿到state對象,才能生成 UI 組件的參數(shù)。
一種解決方法是將state對象作為參數(shù),傳入容器組件。但是,這樣做比較麻煩,尤其是容器組件可能在很深的層級,一級級將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的所有子組件就默認(rèn)都可以拿到state了。
它的原理是React組件的context屬性,請看源碼:
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。\
實例:計數(shù)器
我們來看一個實例。下面是一個計數(shù)器組件,它是一個純的 UI 組件。
class Counter extends Component { ? render() { ? ? const { value, onIncreaseClick } = this.props ? ? return ( ? ? ? <div> ? ? ? ? <span>{value}</span> ? ? ? ? <button onClick={onIncreaseClick}>Increase</button> ? ? ? </div> ? ? ) ? } }
上面代碼中,這個 UI 組件有兩個參數(shù):value和onIncreaseClick。前者需要從state計算得到,后者需要向外發(fā)出 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') );
到此這篇關(guān)于React項目中使用Redux的 react-redux的文章就介紹到這了,更多相關(guān)React 使用 react-redux內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決React報錯Parameter 'props' implicitly&nb
這篇文章主要為大家介紹了React報錯Parameter 'props' implicitly has an 'any' type的解決處理方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12React數(shù)據(jù)傳遞之組件內(nèi)部通信的方法
這篇文章主要介紹了React數(shù)據(jù)傳遞之組件內(nèi)部通信的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12react-redux集中式狀態(tài)管理及基本使用與優(yōu)化
react-redux把組件分為兩類,一類叫做UI組件,一類叫做容器組件,這篇文章主要介紹了集中式狀態(tài)管理<react-redux>基本使用與優(yōu)化,需要的朋友可以參考下2022-08-08解決React在安裝antd之后出現(xiàn)的Can''t resolve ''./locale''問題(推薦)
這篇文章主要介紹了解決React在安裝antd之后出現(xiàn)的Can't resolve './locale'問題,本文給大家分享解決方案,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05