使用react+redux实现弹出框案例( 二 )


  1. 创建 src/store/reducers/modal.reducers.js 文件,把弹出框的reducer抽离出来
import { SHOWMODAL, HIDEMODAL } from './../const/modal.const'const initialState = {show: false}// eslint-disable-next-line import/no-anonymous-default-exportexport default (state = initialState, action) => {switch (action.type) {case SHOWMODAL:return {...state,show: true}case HIDEMODAL:return {...state,show: false}default:return state}}
  1. 创建src/store/reducers/root.reducers.js 文件,用于合并计数器与弹出框的reducer
import { combineReducers } from 'redux'import CounterReducers from './counter.reducers'import ModalReducers from './modal.reducers'// 要求我们传递一个对象 这个对象是状态对象// 这样写了之后 状态的结构将是这样 counter: { count: 0 } modaler: { show: false }export default combineReducers({counter: CounterReducers,modaler: ModalReducers})
  1. 因为使用 combineReducers 合并reducer的时候改变了state的结构所以我们需要在组件中去更改获取state的方式
// src/components/Count.jsconst mapStateProps = ({ counter }) => ({count: counter.count,a: '1'})// src/components/Modal.jsconst mapStateToProps = ({ modaler }) => {return {showState: modaler.show}}【使用react+redux实现弹出框案例】

经验总结扩展阅读