如何获得对象数组的一部分输入的当前值?

时间:2019-05-07 05:36:58

标签: javascript reactjs ecmascript-6 redux

所以我试图用数据填充数组。我面临一个问题。

1-我试图为对象数组中的每个正确键找到一个index。但是,一旦添加了新的输入,我就会收到错误消息。是的,我也动态添加输入。

输入得到很好的添加。

例如,这是在将数据发送到后端之前应该如何看待。这样,最终对象应如何成形:

{
  "previous_investments" : [
      {"name" : "A Name", "amount" : 10000},
      {"name" : "Some Name", "amount" : 35000}
  ]
}

似乎很简单,但我很难受。

这是我主要组件的外观:

const PreviousInvestments = ({
  startupFourthStepForm,
  previousInvestmentsInputs,
  startupFourthStepFormActionHandler,
  previousInvestmentsInputsActionHandler,
}) => {
  const handleMoreInputs = async () => {
    await startupFourthStepFormActionHandler(
      startupFourthStepForm.previous_investments.push({
        name: '',
        amount: undefined,
      }),
    );
    await previousInvestmentsInputsActionHandler(
      `previous_investments-${previousInvestmentsInputs.length}`,
    );
  };

  return (
    <div className="previous-investments-inputs">
      <p>Previous Investments</p>
      {previousInvestmentsInputs.map((input, index) => (
        <div key={input}>
          <FormField
            controlId={`name-${index}`}
            onChange={e => {
              startupFourthStepFormActionHandler({
                // HERE IS WHERE I THINK I AM PROBABLY FAILING
                previous_investments: [{ name: e.currentTarget.value }],
              });
            }}
            value={startupFourthStepForm.previous_investments[index].name}
          />
        </div>
      ))}      
      <Button onClick={() => handleMoreInputs()}>
        + Add more
      </Button>    
    </div>
  );
};

export default compose(
  connect(
    store => ({
      startupFourthStepForm:
        store.startupApplicationReducer.startupFourthStepForm,
      previousInvestmentsInputs:
        store.startupApplicationReducer.previousInvestmentsInputs,
    }),
    dispatch => ({
      previousInvestmentsInputsActionHandler: name => {
        dispatch(previousInvestmentsInputsAction(name));
      },
      startupFourthStepFormActionHandler: value => {
        dispatch(startupFourthStepFormAction(value));
      },
    }),
  ),
)(PreviousInvestments);

在上面的代码中,此按钮添加了一个新输入,并使用函数handleMoreInputs向该数组添加了一个新对象:

      <Button onClick={() => handleMoreInputs()}>
        + Add more
      </Button>  

这是减速器

const initialState = {
  startupFourthStepForm: {
    previous_investments: [{ name: '', amount: undefined }],
  },

  previousInvestmentsInputs: ['previous_investments-0'],
}

const handlers = {
  [ActionTypes.STARTUP_FOURTH_STEP_FORM](state, action) {
    return {
      ...state,
      startupFourthStepForm: {
        ...state.startupFourthStepForm,
        ...action.payload.startupFourthStepForm,
      },
    };
  },

  [ActionTypes.PREVIOUS_INVESTMENTS_INPUTS](state, action) {
    return {
      ...state,
      previousInvestmentsInputs: [
        ...state.previousInvestmentsInputs,
        action.payload.previousInvestmentsInputs,
      ],
    };
  },
}

有趣的是,我能够输入第一个输入,并且一切顺利。但是,一旦添加了新的输入(第二个输入),就会出现此错误:

  

TypeError:无法读取未定义的属性“名称”

     

43 | controlId = {startupFourthStepForm.previous_investments [index] .name}

你觉得我想念什么?

1 个答案:

答案 0 :(得分:1)

ActionTypes.STARTUP_FOURTH_STEP_FORM的处理程序定义为在有效负载中与startupFourthStepForm的对象一起调用并有效地替换它。

在调用此处理程序的地方,您需要确保通过将previous_investments字段与新值合并来调用它

startupFourthStepFormActionHandler({
   ...startupFourthStepForm,
   previous_investments: [
     ...startupFourthStepForm.previous_investments.slice(0, index),
     {
       ...startupFourthStepForm.previous_investments[index],
       name: e.currentTarget.value
     },
     ...startupFourthStepForm.previous_investments.slice(index+1,)
   ],
});

我建议将这种状态更新从处理程序重构到化简器,以便对存储的更新反映在同一位置。 这可以通过将index中项目的previous_investments作为ActionTypes.STARTUP_FOURTH_STEP_FORM动作的有效负载的一部分来传递。