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)