14-多个Reducers在React-Redux中的使用

Time: 20200129

新增一个Ice Cream相关的组件以及Actions, Reducers。

iceCreamTypes.js

export const BUY_ICECREAM = 'BUY_ICECREAM'

iceCreamActions.js

import { BUY_ICECREAM } from './iceCreamTypes'

export const buyIceCream = () => {
    return {
        type: BUY_ICECREAM
    }
}

iceCreamReducer.js

import { BUY_ICECREAM } from './iceCreamTypes'

const initialState = {
    numOfIceCream: 20,
}

const iceCreamReducer = (state = initialState, action) => {
    switch (action.type) {
        // 分情况根据action对state进行操作
        case BUY_ICECREAM:
            return {
                ...state,
                numOfIceCream: state.numOfIceCream - 1
            }
        default:
            return state
    }
}
export default iceCreamReducer

然后综合到一个rootReducer.js中:

rootReducer.js

import { combineReducers } from 'redux'
import cakeReducer from './cake/cakeReducer'
import iceCreamReducer from './iceCream/iceCreamReducer'

export const rootReducer = combineReducers({
    cake: cakeReducer, 
    iceCream: iceCreamReducer
})

此时的store.js:

store.js

import { createStore } from 'redux'
import { rootReducer } from './rootReducer'

const store = createStore(rootReducer)

export default store

上面都是在准备存储相关的内容。

然后在组件端,要能访问同时通过分发动作来修改存储的状态。

IceCreamContainer.js

import React from 'react'
import { buyIceCream } from '../redux'
import { connect } from 'react-redux'

function IceCreamContainer(props) {
    return (
        

Number of Ice Creams - {props.numOfIceCream}

) } // 注意拆分reducers后,访问state.iceCream才是拿到该区间的方式 const mapStatetoProps = state => { return { numOfIceCream: state.iceCream.numOfIceCream } } const mapDispatchToProps = dispatch => { return { buyIceCream: () => dispatch(buyIceCream()) } } export default connect( mapStatetoProps, mapDispatchToProps) (IceCreamContainer)

mapStatetoPropsmapDispatchToProps会将访问存储状态和修改存储的句柄映射到当前组件。

然后当前组件就可以通过props.xxx拿到访问状态权限和修改状态权限。

注意,合并reducer后,会把状态按照:

export const rootReducer = combineReducers({
    cake: cakeReducer, 
    iceCream: iceCreamReducer
})

的键来切分状态空间。

所以,我们可以看到:

const mapStatetoProps = state => {
    return {
        numOfIceCream: state.iceCream.numOfIceCream
    }
}

映射到props后,当前组件访问则就是:props.numOfIceCream即可,这个键是在mapStateToProps中设定的。

真的是很啰嗦了,希望讲得足够清楚。

END.

你可能感兴趣的:(14-多个Reducers在React-Redux中的使用)