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