【问题标题】:How can I get the current value of an input which is part of an array of objects?如何获取作为对象数组一部分的输入的当前值?
【发布时间】:2019-09-24 17:38:27
【问题描述】:

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

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}

你觉得我错过了什么?

【问题讨论】:

    标签: javascript reactjs ecmascript-6 redux


    【解决方案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,)
       ],
    });
    

    我建议将这部分状态更新从处理程序重构到减速器,以便对存储的更新反映在 co-located 中。 这可以通过将previous_investments 中项目的index 作为ActionTypes.STARTUP_FOURTH_STEP_FORM 操作的有效负载的一部分传递来完成。

    【讨论】:

    • 我觉得你有点搞混了。如果您仔细观察,previous_investmentspreviousInvestmentsInputs 的用法不同,这就是两者名称不同的原因。
    猜你喜欢
    • 1970-01-01
    • 2018-04-02
    • 2013-03-07
    • 2022-08-19
    • 1970-01-01
    • 2015-11-20
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多