在 reactjs 的现有状态中动态添加对象变量(使用功能组件)

Add dynamically object variable in existing state in reactjs (Using functional components)

我是 reactjs 的新手,正在创建小项目,我使用的是功能组件而不是 class 组件,并且使用存储来存储状态。我已经添加了一些状态变量并想在退出状态下添加对象数组,我试过了但它不起作用。下面是我的商店文件,其中设置状态:

export const initialState = {
  validationTally: 0,
  token: '',
  multiForm : []
  }

  // action types
const SET_VALIDATION_TALLY = 'SET_VALIDATION_TALLY';
const SET_TOKEN = 'SET_TOKEN';
const SET_MULTIFORM = 'SET_MULTIFORM';

export const reducer = (state, action) => {
    switch (action.type) {
        case SET_VALIDATION_TALLY:
          return {
            ...state,
            validationTally: state.validationTally + 1
          };
        case SET_TOKEN:
          return {
            ...state,
            token: action.payload
          };
        case SET_MULTIFORM:
          return {
            ...state,
            multiForm: action.payload
        };
    }
}

export const setValidationTally = () => ({
  type: SET_VALIDATION_TALLY
});

export const setToken = payload => ({
  type: SET_TOKEN,
  payload
});

export const setMultiForm = payload => ({
  type: SET_MULTIFORM,
  payload
});

我想在状态变量 "multiForm" 中动态添加对象,当有人输入值 2 我想在 "multiForm" 中添加两个对象,如下所示

export const initialState = {
  validationTally: 0,
  app: '',
  token: '',
  multiForm : [{
    firstName : '',   
    lastName :''
  },
  {
    firstName : '',   
    lastName :''
  }]
  }

假设 action.payload for SET_MULTIFORM 操作包含要添加的字段数,您可以简单地映射数组项并添加到现有字段

case SET_MULTIFORM:
      return {
        ...state,
        multiForm: [...state.multiForm, ...Array.from({ length: action.payload }).map(() => ({firstName: '', lastName: ''}))]
    };