ReactJS:将新对象附加到具有传播的现有数组

ReactJS: Appending new object to an existing array with spread

我有这个数组对象开始

[
  {
    "name": "child",
    "pax": {}
  }
]

我想追加新的属性,这是一个数组。然后我想 update/insert 新对象到那个数组中。但是我的代码有问题

function App() {
  const [num, setNum] = useState(0);
  const [arr, setArr] = useState([
    {
      name: "child",
      pax: {}
    }
  ]);

  function appendage({ id, age }) {
    const toSaveArr = arr.map(o => {
      if (o.name === "child") {
        return {
          ...o,
          age: o.age
            ? o.age.map(o2 => {
                if (o2.id === id) {
                  return {
                    id: o2.id,
                    age
                  };
                }
                console.log("o2", o2);
                //something is wrong here
                //why is it not adding new object?
                return [
                  ...o2,
                  {
                    id,
                    age
                  }
                ];
              })
            : [{ id, age }]
        };
      }
      return o;
    });

    setArr(toSaveArr);
  }

  return (
    <div className="App">
      <h1>{num}</h1>
      <button
        onClick={() => {
          setNum(num + 1);

          appendage({
            id: num + 1,
            age: num + 1
          });
        }}
      >
        add
      </button>
      <button>update age where id equal to 2</button>
      <pre>{JSON.stringify(arr, null, 2)}</pre>
    </div>
  );
}

https://codesandbox.io/s/pedantic-mclean-107q2

我想我在这里错误地使用了扩展运算符。

问题是您传递给 map returns 数组的函数,但这不是 map 的工作方式。您只能更改数组中的现有对象,而不能添加新对象。你可以做的是使用例如 find 来搜索数组中的对象并检查结果是否为 undefined.

const result = o.age.find(o2 => o2.id === id);
if (result) {
    result.age = age;
} else {
    o.age.push({ id: o2.id, age: age });
}

您可以在数组中使用 find 方法来查找此处的特定值 "child":

import React, { useState, useDebugValue } from "react";
import styled from "styled-components";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const [num, setNum] = useState(0);
  const [arr, setArr] = useState([
    {
      name: "child",
      pax: []
    }
  ]);

  function appendage({ id, age }) {
    var newarr = arr;
    var add = {
      id: id,
      age: age
    };
    newarr.find(el => el.name === "child").pax = [
      ...newarr.find(el => el.name === "child").pax,
      add
    ];

    setArr(newarr);
  }

  return (
    <div className="App">
      <h1>{num}</h1>
      <button
        onClick={() => {
          setNum(num + 1);

          appendage({
            id: num + 1,
            age: num + 1
          });
        }}
      >
        add
      </button>
      <button>update age where id equal to 2</button>
      <pre>{JSON.stringify(arr, null, 2)}</pre>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

我们检查是否已经有年龄对象,如果是,我们使用扩展运算符添加一个新对象;如果不是,我们插入对象;

相关代码:

import React, { useState } from "react";
import styled from "styled-components";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const [num, setNum] = useState(0);
  const [arr, setArr] = useState([
    {
      name: "child",
      pax: {}
    }
  ]);

  function appendage({ id, age }) {
    console.log("inside appendage with ", id, " and age:", age);
    const toSaveArr = arr.map(o => {
      if (o.name === "child") {
        if (o.age) {
          console.log("age exists");
          o.age = [
            ...o.age,
            {
              id: id,
              age: age
            }
          ];
          console.log("O", o);
        } else {
          o.age = [
            {
              id: id,
              age: age
            }
          ];
          console.log("O", o);
        }
        /*return {
          ...o,
          age: o.age
            ? o.age.map(o2 => {
                if (o2.id === id) {
                  return {
                    id: o2.id,
                    age
                  };
                }
                console.log("o2", o2);
                //something is wrong here
                //why is it not adding new object?
                return [
                  ...o2,
                  {
                    id,
                    age
                  }
                ];
              })
            : [{ id, age }]
        };
      */
      }
      return o;
    });

    setArr(toSaveArr);
  }

  return (
    <div className="App">
      <h1>{num}</h1>
      <button
        onClick={() => {
          setNum(num + 1);

          appendage({
            id: num + 1,
            age: num + 1
          });
        }}
      >
        add
      </button>
      <button>update age where id equal to 2</button>
      <pre>{JSON.stringify(arr, null, 2)}</pre>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

工作codesandbox here