如何通过在React JS中的映射中将新元素添加到对象数据的数组中

huangapple go评论58阅读模式
英文:

How to add new element into Array of object data through mapping in React JS

问题

export default function App() {
  const measurementData = {
    id: 301,
    name: "Topwear",
    measurements: [
      { id: 1, name: "neck" },
      { id: 2, name: "shoulder" }
    ]
  };

  const handleInputChange = (event, id) => {
    const { value } = event.target;
    const updatedMeasurements = measurementData.measurements.map((item) => {
      if (item.id === id) {
        return { ...item, value: Number(value) };
      }
      return item;
    });

    measurementData.measurements = updatedMeasurements;
  };

  return (
    <div className="App mt-5">
      <h1>Update Measurement Data</h1>
      {measurementData.measurements?.map((data) => {
        return (
          <div className="d-flex" key={data.id}>
            <label className="col-form-label">{data.name}</label>
            <input
              type="number"
              name={data.name}
              className="form-control"
              onChange={(e) => handleInputChange(e, data.id)}
            />
          </div>
        );
      })}
    </div>
  );
}
英文:
export default function App() {
  const measurementData = {
    id: 301,
    name: &quot;Topwear&quot;,
    measurements: [
      { id: 1, name: &quot;neck&quot; },
      { id: 2, name: &quot;shoulder&quot; }
    ]
  };

  return (
    &lt;div className=&quot;App mt-5&quot;&gt;
      &lt;h1&gt;Update Measurement Data&lt;/h1&gt;
      {measurementData.measurements?.map((data) =&gt; {
        return (
          &lt;div className=&quot;d-flex&quot;&gt;
              &lt;label className=&quot;col-form-label&quot;&gt;{data.name}&lt;/label&gt;
              &lt;input type=&quot;number&quot; name={data.name} className=&quot;form-control&quot;/&gt;
          &lt;/div&gt;
        );
      })}
    &lt;/div&gt;
  );
}

Basically, I'm mapping through the object.
I just want to add new property called value and save the value that we get from the input field(value: 20) in the end of measurements array of object in measurementData.

// example: the object should be like this after enter values in input field

  {
      id: 301,
      name: &quot;Topwear&quot;,
      measurements: [
        { id: 1, name: &quot;neck&quot;, value: 20},
        { id: 2, name: &quot;shoulder&quot;, value: 40 }
      ]
  }

Some UI example

答案1

得分: 1

你可以通过为 measurements 创建一个状态来实现这一点。这样做可以让 React 在用户在输入框中输入内容时重新渲染用户界面。我将 measurementData 的代码移出组件,如果这是动态的,你可以简单地将它放回原处。

当对 measurements 进行映射以渲染它们时,我们使用 value 属性为输入框提供当前测量的值。如果尚无值,我们默认使用 0

import { useState } from "react";

const measurementData = {
  id: 301,
  name: "Topwear",
  measurements: [
    { id: 1, name: "neck" },
    { id: 2, name: "shoulder" },
  ],
};

export default function App() {
  // 创建状态
  const [measurements, setMeasurements] = useState(
    measurementData.measurements
  );

  // 创建 onChange 处理函数
  const handleOnChange = (e) => {
    const value = e.target.value;
    const name = e.target.name;
    setMeasurements((prevState) => {
      // 遍历先前的测量值
      return prevState.map((measurement) => {
        // 如果名称不同,只返回原来的测量值
        if (measurement.name !== name) return measurement;
        // 否则返回一个新对象,包含原测量值和新值
        return {
          ...measurement,
          value: value,
        };
      });
    });
  };

  return (
    <div className="App mt-5">
      <h1>更新测量数据</h1>
      {measurements.map((measurement) => {
        return (
          <div className="d-flex">
            <label className="col-form-label">{measurement.name}</label>
            <input
              type="number"
              name={measurement.name}
              value={measurement.value ?? 0}
              onChange={handleOnChange}
              className="form-control"
            />
          </div>
        );
      })}
    </div>
  );
}
英文:

You can do this by creating a state for the measurements. This allows React to re-render the UI when the user types something in the inputs. I moved the measurementData code outside the component, if this is dynamic you can simply place it back.

When mapping over the measurements to render them we provide the inputs with a value prop and pass the current value for that measurement. If there is no value yet we default to 0.

import { useState } from &quot;react&quot;;

const measurementData = {
  id: 301,
  name: &quot;Topwear&quot;,
  measurements: [
    { id: 1, name: &quot;neck&quot; },
    { id: 2, name: &quot;shoulder&quot; },
  ],
};

export default function App() {
  // create the state
  const [measurements, setMeasurements] = useState(
    measurementData.measurements
  );

  // create the onChange handler
  const handleOnChange = (e) =&gt; {
    const value = e.target.value;
    const name = e.target.name;
    setMeasurements((prevState) =&gt; {
      // map over the prev measurements
      return prevState.map((measurement) =&gt; {
        // if the name is not the same just return the measurement
        if (measurement.name !== name) return measurement;
        // else return a new object with the prev measurement and the new value
        return {
          ...measurement,
          value: value,
        };
      });
    });
  };

  return (
    &lt;div className=&quot;App mt-5&quot;&gt;
      &lt;h1&gt;Update Measurement Data&lt;/h1&gt;
      {measurements.map((measurement) =&gt; {
        return (
          &lt;div className=&quot;d-flex&quot;&gt;
            &lt;label className=&quot;col-form-label&quot;&gt;{measurement.name}&lt;/label&gt;
            &lt;input
              type=&quot;number&quot;
              name={measurement.name}
              value={measurement.value ?? 0}
              onChange={handleOnChange}
              className=&quot;form-control&quot;
            /&gt;
          &lt;/div&gt;
        );
      })}
    &lt;/div&gt;
  );
}

huangapple
  • 本文由 发表于 2023年2月6日 03:20:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75354894.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定