reactjs 如何在React JS中通过Map向对象数据的Array中添加新元素

ecbunoof  于 2023-02-08  发布在  React
关注(0)|答案(1)|浏览(227)
export default function App() {
  const measurementData = {
    id: 301,
    name: "Topwear",
    measurements: [
      { id: 1, name: "neck" },
      { id: 2, name: "shoulder" }
    ]
  };

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

基本上,我是通过对象进行Map的,我只想添加一个名为value的新属性,并保存从输入字段(value:20)在measurementData中对象的测量数组的末尾。
//示例:在输入字段中输入值后,对象应如下所示

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

Some UI example

2w2cym1i

2w2cym1i1#

您可以通过为measurements创建一个状态来实现这一点。这允许React在用户在输入中键入内容时重新呈现UI。我将measurementData代码移到组件外部,如果这是动态的,您可以简单地将其放回原处。
当Map到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() {
  // create the state
  const [measurements, setMeasurements] = useState(
    measurementData.measurements
  );

  // create the onChange handler
  const handleOnChange = (e) => {
    const value = e.target.value;
    const name = e.target.name;
    setMeasurements((prevState) => {
      // map over the prev measurements
      return prevState.map((measurement) => {
        // 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 (
    <div className="App mt-5">
      <h1>Update Measurement Data</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>
  );
}

相关问题