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-Native之TextInput組件的設(shè)置以及如何獲取輸入框的內(nèi)容
這篇文章主要介紹了React-Native之TextInput組件的設(shè)置以及如何獲取輸入框的內(nèi)容問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05
React 進(jìn)入頁面后自動 focus 到某個輸入框的解決方案
React.js 當(dāng)中提供了 ref 屬性來幫助我們獲取已經(jīng)掛載的元素的 DOM 節(jié)點,你可以給某個 JSX 元素加上 ref屬性,這篇文章主要介紹了React 進(jìn)入頁面以后自動 focus 到某個輸入框,需要的朋友可以參考下2024-02-02

