简体   繁体   English

更新 React state 中的嵌套数组

[英]Updating nested array in React state

While the onChange works as expected the features are not being updated in state.虽然 onChange 按预期工作,但 state 中的功能并未更新。 After many attempts I thought id ask as I'm having trouble finding examples similar to what I'm trying to do.经过多次尝试后,我想我会问,因为我很难找到与我正在尝试做的事情相似的例子。

Array of objects (In this case one object for simplicity sake)对象数组(为简单起见,在本例中为一个 object)

const data = [{
    name: 'Starter',
    featured: false,
    price: { Monthly: '$49', Quarterly: '$129', Annually: '$379' },
    description: 'You’re new to the gym but want to do it right.',
    button: {
      label: 'Subscribe',
      href: '/register',
    },
    features: ['Full gym access'],
    logomarkClassName: 'fill-gray-300'}]

Map Map

{plans[0].features.map((feature, index) => (
  <div key={index}>
    <input
      value={feature}
      onChange={(e) => {
        feature = e.target.value
        setPlans([...plans])
      }}
    />
  </div>
))}

I am able to update the price object using the code below but having trouble with features as it is an array.我可以使用下面的代码更新 object 的价格,但由于它是一个数组,所以在功能方面存在问题。

onChange={(e) => {
  plans[0].price.Annually =
  e.target.value
  setPlans([...plans])
}}

UI用户界面

![在此处输入图像描述

You must have at least two states, plans and selectedPlan .您必须至少有两个状态,计划selectedPlan The plans state will keep the whole data and selectedPlan that holds the selected membership that will be edited.计划state 将保留整个数据和selectedPlan ,其中包含将被编辑的选定成员资格。

The edit form will show the selectedPlan and when the user edits the information it should not update the main plans state directly but update the selectedPlan instead.编辑表单将显示selectedPlan ,当用户编辑信息时,它不应直接更新主计划state,而是更新selectedPlan The plans state will only be updated if the user clicks the "Update button" (where your image is shown as a created button).计划state 只有在用户单击“更新按钮”(您的图像显示为创建按钮)时才会更新。

  const updatePlans = useCallback(() => {
    const updatedPlans = [...plans];
    updatedPlans[selectedPlan.id] = selectedPlan;
    setPlans(updatedPlans);
    setSelectedPlan();
  }, [plans, selectedPlan]);

Here, we clone the plans and update the selected plan with an id property as a helper.在这里,我们克隆计划并使用id属性作为助手更新所选计划。

To update the features array in a controlled input, you can use toString() method at the value , and at onChange you can split the input.要更新受控输入中的特征数组,可以在value处使用toString()方法,在onChange处可以拆分输入。

  <input
    value={selectedPlan.features.toString()}
    onChange={(e) => {
      setSelectedPlan((prevState) => {
        return { ...prevState, features: e.target.value.split(",") };
      });
    }}
  />

you can see the minimal example here:你可以在这里看到最小的例子:

编辑 nifty-golick-jhvy35

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM