简体   繁体   English

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

[英]ReactJS: Appending new object to an existing array with spread

I have this array object to begin with 我有这个数组对象开始

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

I wish to append new property which is an array. 我希望附加一个数组的新属性。 then I want to update/insert new object into that array. 那么我想将新对象更新/插入该数组。 But something is wrong with my code 但是我的代码出了点问题

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 https://codesandbox.io/s/pedantic-mclean-107q2

I think I've used spread operator wrongly here. 我想我在这里错误地使用了传播算子。

The problem is that the function you pass into map returns an array, but that is not how map works. 问题是传递给map的函数返回一个数组,但这不是map工作方式。 You can only change existing objects in the array, but not add new ones. 您只能更改数组中的现有对象,而不能添加新对象。 What you can do is use for example find to search for the object in the array and check if the result is undefined . 您可以使用例如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 });
}

you can use find method in your array to find specific value which is here "child" : 您可以在数组中使用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);

we check to see if there is already an age object, if yes, we add a new object using spread operator; 我们检查是否已经存在年龄对象,如果是,则使用传播运算符添加一个新对象; if no, we insert the object; 如果没有,我们插入对象;

relevant code : 相关代码

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);

working codesandbox here 这里的工作代码和盒子

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

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