简体   繁体   English

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

[英]How can I get the current value of an input which is part of an array of objects?

So I am trying to fill an array with data. 所以我试图用数据填充数组。 I am facing one problem. 我面临一个问题。

1 - I am trying to find an index for every proper key in the array of objects. 1-我试图为对象数组中的每个正确键找到index But I get an error once a new input is added. 但是,一旦添加了新的输入,我就会收到错误消息。 Yes, I am adding inputs dynamically too. 是的,我也正在动态添加输入。

The inputs gets added well. 输入得到很好的添加。

This is for example, how the data should look before been send to the backend. 例如,这就是在将数据发送到后端之前应该如何看待。 Like this is how the final object should be shaped: 这样,最终对象应如何成形:

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

Seems to be easy but I am having a hard time. 似乎很容易,但是我很难过。

This is how my main component looks: 这是我的主要组件的外观:

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);

In the code above, this button adds a new input and also it adds a new object to the array using the function handleMoreInputs : 在上面的代码中,此按钮添加了一个新的输入,并且还使用handleMoreInputs函数handleMoreInputs数组添加了一个新对象:

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

This is the reducer: 这是减速器:

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,
      ],
    };
  },
}

The funny thing is that I am able to type in the first input and everything goes well. 有趣的是,我能够输入第一个输入,并且一切顺利。 But once I add a new input, a second one, I get this error: 但是,一旦添加了新的输入(第二个输入),就会出现此错误:

TypeError: Cannot read property 'name' of undefined TypeError:无法读取未定义的属性“名称”

43 | 43 | controlId={startupFourthStepForm.previous_investments[index].name} 控件ID = {startupFourthStepForm.previous_investments [指数]。名称}

Wo what do you think I am missing? 我觉得我想念什么?

The handler for ActionTypes.STARTUP_FOURTH_STEP_FORM is defined to be invoked with an object for startupFourthStepForm in the payload and effectively replace it. ActionTypes.STARTUP_FOURTH_STEP_FORM的处理程序定义为与有效负载中的startupFourthStepForm的对象一起调用并有效地替换它。

Where this handler is invoked, you need to ensure that it is called with previous_investments field merged with the new value 在调用此处理程序的地方,您需要确保使用合并了新值的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,)
   ],
});

I suggest to refactor away this piece of state update from the handler to the reducer so that updates to the store are reflected in co-located. 我建议将这一状态更新从处理程序重构到reducer,以便对存储的更新反映在同一位置。 This can be done by passing the index of the item in previous_investments as a part of the payload for ActionTypes.STARTUP_FOURTH_STEP_FORM action. 这可以通过将previous_investments中的项目index作为ActionTypes.STARTUP_FOURTH_STEP_FORM操作的有效负载的一部分传递来完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取输入数组的值 - How can I get value of input array 我怎样才能在 Vue 的变化中获得当前输入值? - how can i get current input value on change in Vue? 如何获取在选择2输入字段上输入的当前输入值 - How to get the current input value which is entering on select 2 input field 如何获取先前兄弟的输入的值? - How can I get the value of an input which is a previous sibling? 如何获取JavaScript中的对象数组内的对象数组的长度? - How can I get the length of an array of objects which is within an array of objects in javascript? 如何更新具有数组的useState,在该数组中我有对象,当输入值在react js中发生变化时,该对象将更新 - How to update a useState which has an array, inside this array I have objects this objects will update when the input value will change in react js 当我移动它时,如何获取范围输入的当前值并在控制台中打印? - How can i get the current value of my range input and print in console when i am moving it? 如何获得具有分配了索引值的数组名称的输入元素? - How to get an input element that has an array name which I have assigned the value of the index? 如何通过我之前获得的索引获得两行或多行输入的值? - How can I get the value of an input of two or more rows through the indexes which I got before? 如何获得对象列表中的值 - How can I get a value in a list of objects
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM