React--工厂模式action分离

store.ts

import { createStore } from 'redux'
import languageReducer form './language/reducer.ts'

const store = createStore(languageReducer)

export default store

工厂模式创建action-actionCreator.ts

/* 用常量定义action.type,减少代码敲错 */
export const ADD_LANGUAGE = 'language/add'
export const CHANGE_LANGUAGE = 'language/change'

/* action的类型申明 */
const AddActionProps = {
  type: typeof ADD_LANGUAGE,
  payload: { code: string, language: string }
}
const ChangeActionProps = {
  type: typeof CHANGE_LANGUAGE,
  payload: 'zh' | 'en'
}

export type LanguageActionProps = AddActionProps | ChangeActionProps

/* 用工厂模式创建action */
export const addLanguageActionCreator = (language: {code: string, language: string}):ADD_LANGUAGE  => {
  return {
    type: ADD_LANGUAGE,
    payload: language
  }
}
export const changeLanguageActionCreator = (lng: 'zh' | 'en'):CHANGE_LANGUAGE  => {
  return {
    type: CHANGE_LANGUAGE,
    payload: lng
  }
}

reducer.ts

import { ADD_LANGUAGE, CHANGE_LANGUAGE, LanguageActionProps } from './actions'

export interface LanguageState {
  lng: 'zh' | 'en',
  languageList: {code: string, language: string}[]
}

const defaultStoreState: LanguageState = {
  lng: 'zh',
  languageList: [{ code: 'zh', language: '中文'}, { code: 'en', language: 'English'}]
}


export default (state = defaultStoreState, action:LanguageActionProps) => {
    switch (action.type) {
    case CHANGE_LANGUAGE:
      return { ...state, lng: action.payload }
    case ADD_LANGUAGE:
      return { ...state, languageList: [...state.languageList, action.payload] }
    default:
      return state
  }
}

组件中使用store

action = changeLanguageActionCreator({code: `lng${nanoid()}`, language: '新语种'})
store.dispatch(action)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值