前言react
本文對redux相關使用的總結,利用一個簡單的計數器應用介紹來flux、redux、react-redux、redux-actions等相關類庫的使用。web
初始代碼 如下是該示例的初始代碼,一個不使用redux的普通計數器應用。npm
import React from 'react'class Calculate extends React.Component {
constructor(props) {
super(props)
this.state = {
count: 0
}
}
increase = () => {
this.setState({
count: this.state.count + 1
})
}
decrease = () => {
this.setState({
count: this.state.count - 1
})
}
render() {
return(
<div>
<h1>{this.state.count}</h1>
<div>
<button type="button" onClick={this.increase}>Increase</button>
<button type="button" onClick={this.decrease}>Decrease</button>
</div>
</div>
)
}}export default Calculate
複製代碼
Fluxredux
React是單向數據流,組件狀態的維護是靠父子組件之間逐層傳遞來實現的,當應用層級較深時,這種方式就會顯得比較繁瑣。對此,社區提出了很多解決的方案,目前的最佳實踐是Redux。編輯器
Redux嚴格意義上來說是Flux的一種簡潔的實現,在介紹Redux以前,咱們先使用flux來重構這個計數器應用。ide
Flux主要流程有4部分,action、dispatcher、store、view,在該示例中咱們須要使用到flux和events兩個npm包來實現。this
首先,在基礎模板上創建目錄以下spa
actionType.js用來定義常量,而後導出,該示例有加和減兩種action。code
export const INCREASE = 'INCREASE'export const DECREASE = 'DECREASE'dispatcher.js用來定義dispatcher並導出component
import { Dispatcher } from 'flux'class CalculateDispatcherClass extends Dispatcher { handleAction(action) { this.dispatch({ type: action.type, payload: action.payload }) }}const CalculateDispatcher = new CalculateDispatcherClass()export default CalculateDispatcher action.js使用導入的action類別以及上面定義的dispatcher來定義action。
複製代碼import { INCREASE, DECREASE} from '../constants/actionTypes'import CalculateDispatcher from '../dispatcher/dispatcher'const action = { increase(value = 1) { CalculateDispatcher.handleAction({ type: INCREASE, payload: value }) }, decrease(value = 1) { CalculateDispatcher.handleAction({ type: DECREASE, payload: value }) }} export default action 複製代碼
最後在store.js中整合
import CalculateDispatcher from '../dispatcher/dispatcher'import { EventEmitter } from 'events'import { INCREASE, DECREASE} from '../constants/actionTypes'const store = { count: 0}class CalculateStoreClass extends EventEmitter { addIncreaseListener(callBack) { this.on(INCREASE, callBack) }addDecreaseListener(callBack) { this.on(DECREASE, callBack) }
複製代碼getStore() { return store }}const CalculateStore = new CalculateStoreClass()CalculateDispatcher.register((action) => { switch(action.type) { case INCREASE: store.count += action.payload CalculateStore.emit(INCREASE) break case DECREASE: store.count -= action.payload CalculateStore.emit(DECREASE) break default: return true } return true})export default CalculateStore 複製代碼
最後calculate.js存放咱們的視圖組件
import React from 'react'import Store from '../store/store'import Action from '../action/action'class Calculate extends React.Component {
constructor(props) {
super(props)
this.state = {
count: 0
}
}
componentDidMount() {
Store.addDecreaseListener(this.updateState)
Store.addIncreaseListener(this.updateState)
}
updateState = () => {
this.setState({
count: Store.getStore().count })
}
increase = () => {
Action.increase()
}
decrease = () => {
Action.decrease()
}
render() {
return(
<div>
<h1>{this.state.count}</h1>
<div>
<button type="button" onClick={this.increase}>Increase</button>
<button type="button" onClick={this.decrease}>Decrease</button>
</div>
</div>
)
}}export default Calculate
複製代碼
Redux
瞭解來Flux以後,就能夠使用Redux了,Redux和Flux的不一樣在與將dispatcher換成了reducer
首先看一下項目結構,與flux的基本沒有區別,只是將dispatcher換成了reducer
該示例中不只使用了redux, 還使用了react-redux,使得redux和react項目更容易結合,使用了redux-actions,使action和reducer中類型的判斷更加簡單。
actionType.js
export const INCREASE = 'INCREASE'export const DECREASE = 'DECREASE' action.js 利用redux-actions來建立action 複製代碼import { INCREASE, DECREASE} from '../constants/actionTypes'import { createActions} from 'redux-actions'const Action = createActions({ [INCREASE]: (value = 1) => ({ payload: value }), [DECREASE]: (value = 1) => ({ payload: value })})export default Action 複製代碼
reducer.js 一樣,利用redux-actions來處理reducer
import { INCREASE, DECREASE } from '../constants/actionTypes'import { handleActions} from 'redux-actions'const reducer = handleActions({
[INCREASE]: (state, action) => (Object.assign({}, state, { count: state.count + action.payload.payload})),
[DECREASE]: (state, action) => (Object.assign({}, state, { count: state.count - action.payload.payload}))}, {
count: 0})export default reducer
複製代碼
store.js 利用redux建立store
import { createStore } from 'redux'import reducer from '../reducer/reducer'const store = createStore(reducer)export default store
複製代碼
calculate.js 利用react-redux來鏈接react和redux
import React from 'react'import Action from '../action/action'import { connect } from 'react-redux'class Calculate extends React.Component {
increase = () => {
this.props.increase()
}
decrease = () => {
this.props.decrease()
}
render() {
return(
<div>
<h1>{this.props.count}</h1>
<div>
<button type="button" onClick={this.increase}>Increase</button>
<button type="button" onClick={this.decrease}>Decrease</button>
</div>
</div>
)
}}const mapStateToProps = (state) => {
return {
count: state.count }}export default connect(mapStateToProps, Action)(Calculate)
複製代碼
最後,在App.js中使用Provider將store傳入
import React from 'react'import Calculate from './component/calculate'import { Provider } from 'react-redux'import store from './store/store'class App extends React.Component {
render() {
return (
<Provider store={store}>
<Calculate />
</Provider>
)
}}export default App
複製代碼
本文使用 mdnice 排版