react简书项目学习笔记28redux拆分redcer,action便于管理

1.当把所有数据以及对数据的操作都放在同一个文件中时,这个文件必须会变得非常大,这样的话设计就显得不够合理。(一般一个文件的代码别超过300行)

const defaultState = {
  focused: false
};

export default (state = defaultState, action) => {
  if (action.type === 'search_focus') {
    return {
      focused: true
    }
  }
  if (action.type === 'search_blur') {
    return {
      focused: false
    }
  }
  return state;
}

解决办法:我们可以对reducer进行拆分
拆分多个文件存放数据,对应的组件可以有对应的reducer
eg,对于header,我们可以在其下创建相应的store文件夹存放其相关reducer
react简书项目学习笔记28redux拆分redcer,action便于管理_第1张图片
combineReducers可以把一些小的reducer合成大的reducer
在src/store/reducer下配置

import { combineReducers } from 'redux';
import headerReducer from '../common/header/store/reducer';

export default combineReducers({
  header: headerReducer
})

因为提交的action类型比较多,如果某个名字出错或者其他错误,可能不能及时发现,解决办法:action统一抽成常量管理(actionCreators)
actionCreators

import * as constants from './constants';
export const searchFocus = () => ({
  type: constants.SEARCH_FOCUS
})

export const searchBlur  = () => ({
  type:  constants.SEARCH_FOCUS
}) 

constants
//actionType统一写成常量放在该文件中

export const SEARCH_FOCUS = 'header/SEARCH_FOUCS';
export const SEARCH_BLUR = '/header/SEARCH_BLUR'

在相关组件中写法

import * as actionCreators from './store/actionCreators';
……
  handleInputFocus() {
      dispatch(actionCreators.searchFocus());
    },

reducer文件

import * as constants from './constants';
const defaultState = {
  focused: false
};

export default (state = defaultState, action) => {
  if (action.type === constants.SEARCH_FOCUS) {
    return {
      focused: true
    }
  }
  if (action.type === constants.SEARCH_BLUR) {
    return {
      focused: false
    }
  }
  return state;
}

import文件时目录层次比较多,解决办法:
在index先引入

//写这个文件可以使得在store/reducer下引入时目录结构少两层
import reducer from './reducer';
import * as actionCreators from './actionCreators';
import * as constants from './constants';
export { reducer, actionCreators, constants };

你可能感兴趣的:(react,前端)