简体   繁体   English

map 覆盖在数组中的嵌套 object

[英]map over nested object in an array

Currently trying to map over an array that has multiple nested objects.目前正在尝试对具有多个嵌套对象的数组进行 map。 When I run the map function, it only returns the outer object.当我运行 map function 时,它只返回外部 object。

在此处输入图像描述

const [moreDetails, setMoreDetails] = useState([]);
const [details, setDetails] = useState("");

const handleAddMoreDetails = () => {
  setMoreDetails((prevState) => [
    {
      ...prevState,
      details: details
    }
  ]);
  setDetails("");
};

return (
  <div className="App">
    <input
      type="text"
      value={details}
      onChange={(e) => setDetails(e.target.value)}
    />

    <button onClick={handleAddMoreDetails}>Add Detail</button>

    {moreDetails &&
      moreDetails.map((item, index) => <p key={index}>{item.details}</p>)}
  </div>
);

This is similar to what I am trying to accomplish.这类似于我想要完成的事情。 I would like for it to render all of them when added.我希望它在添加时渲染所有这些。 I am thinking it may be the one I am trying to add a new detail我想这可能是我试图添加新细节的那个

CodeSandbox 代码沙盒

The problem isn't in the rendering, it's in the state update:问题不在于渲染,而在于 state 更新:

setMoreDetails((prevState) => [
  {
    ...prevState,
    details: details
  }
]);

If prevState was an array, for example:如果prevState是一个数组,例如:

[
  { details: 'first record' }
]

Then what happens after your state update?那么在您的 state 更新后会发生什么? This update is creating an array with one object , which contains both the previous array and the new object.此更新正在创建一个包含一个 object的数组,其中包含以前的数组和新的 object。 So the new result is:所以新的结果是:

[
  {
    0: {
      details: 'first record'
    },
    details: 'second record'
  }
]

Each update to the state will continue to create an array with one object, nesting the previous array inside that object. state 的每次更新都将继续创建一个包含一个 object 的数组,将前一个数组嵌套在该 object 中。

Instead, create an array containing the elements of the previous array plus the one new object:相反,创建一个包含前一个数组的元素加上一个新的 object 的数组:

setMoreDetails((prevState) => [
  ...prevState,
  {
    details: details
  }
]);

So the new state would be:所以新的 state 将是:

[
  { details: 'first record' },
  { details: 'second record' }
]

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

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