react reducer 项目的如何的简化的代码
import {
ADD_TODO_ITEM,
CHANG_INPUT_VALUE,
DELETE_TODO_ITEM
} from './actionType'
class Reducer {
actionType = {
[CHANG_INPUT_VALUE]: (state, value) => {
const newState = JSON.parse(JSON.stringify(state))
newState.inputValue = value
return newState
},
[ADD_TODO_ITEM]: state => {
const newState = JSON.parse(JSON.stringify(state))
if(!newState.inputValue.length) {
message.warn('请输入内容')
return
}
newState.todoList.push(state.inputValue)
newState.inputValue = ''
return newState
},
[DELETE_TODO_ITEM]: (state, value) => {
const newState = JSON.parse(JSON.stringify(state))
newState.todoList.splice(value, 1)
return newState
}
}
getReducer(state, action) {
try {
const { type, value } = action
return this.actionType[type](state, value)
} catch (error) {
console.warn(error.message)
return state
}
}
}
const defaultState = {
todoList: [],
inputValue: ''
}
export default (state = defaultState, action) => {
return new Reducer().getReducer(state, action)
}
以上代码 Reducer 类中 actionType 对象的上的每一个方法都重复了以下的代码
const newState = JSON.parse(JSON.stringify(state))
return newState
这两行代码的就是在每个方法中 都会存在 如何进行简化
注意: 这里我是用了装饰器的模式 但是改造不成功
以下是使用装饰器模式进行改造但是没有的改造成功
function nameDecorator(target, key, descriptor) {
const temp = descriptor.initializer()
const fnObject = {}
Object.keys(temp).forEach((fn, index) => {
try {
const fnString = temp[fn].toString()
const fnStringReplace = fnString.replace('state', 'oldState')
const fnStringSplit = fnStringReplace.split('\n')
fnStringSplit[0] = fnStringSplit[0] + `const newState = JSON.parse(JSON.stringify(oldState));`
fnStringSplit[fnStringSplit.length - 2] = fnStringSplit[fnStringSplit.length - 2] + `return newState`
const fnStringJoin = fnStringSplit.join('')
const tempFnString = fnStringJoin.replaceAll(' ', '')
const fnStringNewState = tempFnString.replaceAll('state', 'newState')
const addFnName = fnStringNewState.replace('function', 'function ' + fn)
fnObject[fn] = new Function('return ' + addFnName)
} catch (error) {
console.error(error)
}
})
console.log(fnObject)
}
@nameDecorator
class Reducer {
actionType = {
[CHANG_INPUT_VALUE]: (state, value) => {
const newState = JSON.parse(JSON.stringify(state))
newState.inputValue = value
return newState
},
[ADD_TODO_ITEM]: state => {
const newState = JSON.parse(JSON.stringify(state))
if(!newState.inputValue.length) {
message.warn('请输入内容')
return
}
newState.todoList.push(state.inputValue)
newState.inputValue = ''
return newState
},
[DELETE_TODO_ITEM]: (state, value) => {
const newState = JSON.parse(JSON.stringify(state))
newState.todoList.splice(value, 1)
return newState
}
}
}