ReactJS:将新对象扩展到现有数组

时间:2019-07-09 06:28:24

标签: javascript arrays reactjs spread-syntax

我有这个数组对象开头

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

我希望添加一个新属性,它是一个数组。那么我想将新对象更新/插入该数组。但是我的代码有问题

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

我认为我在这里错误地使用了传播算子。

3 个答案:

答案 0 :(得分:0)

问题在于您传递给map的函数返回一个数组,但这不是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 });
}

答案 1 :(得分:0)

您可以在数组中使用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);

答案 2 :(得分:0)

我们检查是否已经存在年龄对象,如果是,则使用散布运算符添加一个新对象;如果没有,我们插入对象;

相关的代码

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