Возможно, если вы используете useReducer
, было бы лучше, если бы у вас было несколько состояний
Пример
const initialState = {
counter: 1,
sizes: [0],
formats: [0],
};
function reducer(state, action) {
switch (action.type) {
case 'add':
return {
...state,
counter: state.counter + 1,
[action.typeObject]: [...state.sizes, state.counter + 1]
};
case 'remove':
return {
...state,
counter: state.counter - 1,
[action.typeObject]: [...state.sizes.filter(item => item !== action.index)]
};
default:
return state;
}
}
/***/
const [stateReducer, dispatch] = React.useReducer(reducer, initialState);
/***/
const addSizesFieldset = () => {
dispatch({ type: 'add', typeObject: 'sizes' })
};
const removeSizesFieldset = index => () => {
dispatch({ type: 'remove', typeObject: 'sizes', index })
};
const addFormatsFieldset = () => {
dispatch({ type: 'add', typeObject: 'formats' })
};
const removeFormatsFieldset = index => () => {
dispatch({ type: 'remove', typeObject: 'formats', index })
};
Проверьте это
Вот моя простая реализация: разветвление вашего кода: https://codesandbox.io/s/react-hook-form-wizard-form-1h4yq
Редактировать:
Вы даже можете удалить 2 функции, добавив «typeObject» в параметре:
const addFieldset = field => () => {
dispatch({ type: 'add', typeObject: field })
};
const removeFieldset = (index, field) => () => {
dispatch({ type: 'remove', typeObject: field, index })
};