react-redux
在react-redux 框架中,給我提供了兩個常用的API來配合Redux框架的使用,其實在我們的實際項目開發(fā)中,我們完全可以不用react-redux框架,但是如果使用此框架,就如虎添翼了。
我們來簡單聊聊這兩個常用的API
- connect()
- Provider 組件
React-Redux 將所有組件分成兩大類:UI 組件(presentational component)和容器組件(container component)。
UI 組件
UI 組件有以下幾個特征。
- 只負責 UI 的呈現(xiàn),不帶有任何業(yè)務邏輯
- 沒有狀態(tài)(即不使用this.state這個變量)
- 所有數(shù)據(jù)都由參數(shù)(this.props)提供
- 不使用任何 Redux 的 API
下面就是一個 UI 組件的例子。
const Title =
value => <h1>{value}</h1>;
因為不含有狀態(tài),UI 組件又稱為"純組件",即它純函數(shù)一樣,純粹由參數(shù)決定它的值。
容器組件
容器組件的特征恰恰相反。
- 負責管理數(shù)據(jù)和業(yè)務邏輯,不負責 UI 的呈現(xiàn)
- 帶有內(nèi)部狀態(tài)
- 使用 Redux 的 API
總之,只要記住一句話就可以了:UI 組件負責 UI 的呈現(xiàn),容器組件負責管理數(shù)據(jù)和邏輯。
你可能會問,如果一個組件既有 UI 又有業(yè)務邏輯,那怎么辦?回答是,將它拆分成下面的結(jié)構(gòu):外面是一個容器組件,里面包了一個UI 組件。前者負責與外部的通信,將數(shù)據(jù)傳給后者,由后者渲染出視圖。
React-Redux 規(guī)定,所有的 UI 組件都由用戶提供,容器組件則是由 React-Redux 自動生成。也就是說,用戶負責視覺層,狀態(tài)管理則是全部交給它。
connect()
React-Redux 提供connect方法,用于從 UI 組件生成容器組件。connect的意思,就是將這兩種組件連起來。
import { connect } from 'react-redux'
const VisibleTodoList = connect()(TodoList);
上面代碼中,TodoList是 UI 組件,VisibleTodoList就是由 React-Redux 通過connect方法自動生成的容器組件。
但是,因為沒有定義業(yè)務邏輯,上面這個容器組件毫無意義,只是 UI 組件的一個單純的包裝層。為了定義業(yè)務邏輯,需要給出下面兩方面的信息。
- 輸入邏輯:外部的數(shù)據(jù)(即state對象)如何轉(zhuǎn)換為 UI 組件的參數(shù)
- 輸出邏輯:用戶發(fā)出的動作如何變?yōu)?Action 對象,從 UI 組件傳出去。
因此,connect方法的完整 API 如下。
import { connect } from 'react-redux'
const VisibleTodoList = connect(
mapStateToProps,
mapDispatchToProps
)(TodoList)
上面代碼中,connect方法接受兩個參數(shù):mapStateToProps和mapDispatchToProps。它們定義了 UI 組件的業(yè)務邏輯。前者負責輸入邏輯,即將state映射到 UI 組件的參數(shù)(props),后者負責輸出邏輯,即將用戶對 UI 組件的操作映射成 Action。
mapStateToProps()
mapStateToProps是一個函數(shù)。它的作用就是像它的名字那樣,建立一個從(外部的)state對象到(UI 組件的)props對象的映射關(guān)系。
作為函數(shù),mapStateToProps執(zhí)行后應該返回一個對象,里面的每一個鍵值對就是一個映射。請看下面的例子。
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,每當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方法的映射。也就是說,它定義了哪些用戶的操作應該當作 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ù),應該返回一個對象,該對象的每個鍵值對都是一個映射,定義了 UI 組件的參數(shù)怎樣發(fā)出 Action。
如果mapDispatchToProps是一個對象,它的每個鍵名也是對應 UI 組件的同名參數(shù),鍵值應該是一個函數(shù),會被當作 Action creator ,返回的 Action 會由 Redux 自動發(fā)出。舉例來說,上面的mapDispatchToProps寫成對象就是下面這樣。
const mapDispatchToProps = {
onClick: (filter) => {
type: 'SET_VISIBILITY_FILTER',
filter: filter
};
}
<Provider> 組件
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的所有子組件就默認都可以拿到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')
);
總結(jié)
本系列教程是參照阮老師的Redux入門教程文章和Redux中文文檔進行的整合和拓展。更多更詳細的Redux使用方式請參照教程一中的參考文獻。
更多文章
- 作者React Native開源項目OneM【500+ star】地址(按照企業(yè)開發(fā)標準搭建框架完成開發(fā)的):https://github.com/guangqiang-liu/OneM:歡迎小伙伴們 star
- 作者簡書主頁:包含60多篇RN開發(fā)相關(guān)的技術(shù)文章http://www.itdecent.cn/u/023338566ca5 歡迎小伙伴們:多多關(guān)注,多多點贊