Notice
Recent Posts
Recent Comments
Link
«   2025/10   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

리액트 정리

[UserList] 배열에 항목 추가하기. Spread연산자와 concat 본문

리액트

[UserList] 배열에 항목 추가하기. Spread연산자와 concat

버그킴 2020. 3. 3. 13:52

1.  spread 연산자:  기존의 배열을 한번 복사하고 나서 새로운 원소 추가. 

2. concat 함수: concat 함수는 기존의 배열을 수정하지 않고, 새로운 원소가 추가된 새로운 배열을 만들어줍니다.

 

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];

const array3 = [{id:1, name:'a'},{id:2, name:'b'},{id:3, name:'c'}]
const object1 = {id:4, name:'d'}


 // ["a", "b", "c", "d", "e", "f"]
console.log(array1.concat(array2))
console.log([...array1, ...array2])


 // [Object { id: 1, name: "a" }, Object { id: 2, name: "b" }, Object { id: 3, name: "c" }, Object { id: 4, name: "d" }]
console.log([...array3, object1])
console.log([...array3, {id:4, name:'d'}])




 

 

 배열에 변화를 줄 때에는 객체와 마찬가지로, 불변성을 지켜주어야 합니다. 그렇기 때문에, 배열의 push, splice, sort 등의 함수를 사용하면 안됩니다. 만약에 사용해야 한다면, 기존의 배열을 한번 복사하고 나서 사용해야합니다.

불변성을 지키면서 배열에 새 항목을 추가하는 방법은 두가지가 있습니다.

첫번째는 spread 연산자를 사용하는 것 입니다.

 

사용 코드 보기

더보기
import React, { useRef, useState } from 'react';
import UserList from './UserList';
import CreateUser from './CreateUser';

function App() {
  const [inputs, setInputs] = useState({
    username: '',
    email: ''
  });
  const { username, email } = inputs;
  const onChange = e => {
    const { name, value } = e.target;
    setInputs({
      ...inputs,
      [name]: value
    });
  };
  const [users, setUsers] = useState([
    {
      id: 1,
      username: 'velopert',
      email: 'public.velopert@gmail.com'
    },
    {
      id: 2,
      username: 'tester',
      email: 'tester@example.com'
    },
    {
      id: 3,
      username: 'liz',
      email: 'liz@example.com'
    }
  ]);

  const nextId = useRef(4);
  const onCreate = () => {
    const user = {
      id: nextId.current,
      username,
      email
    };
    setUsers([...users, user]);

    setInputs({
      username: '',
      email: ''
    });
    nextId.current += 1;
  };
  return (
    <>
      <CreateUser
        username={username}
        email={email}
        onChange={onChange}
        onCreate={onCreate}
      />
      <UserList users={users} />
    </>
  );
}

export default App;

자, 새 항목이 잘 등록되는지 확인해보세요.

또 다른 방법은 concat 함수를 사용하는 것 입니다. concat 함수는 기존의 배열을 수정하지 않고, 새로운 원소가 추가된 새로운 배열을 만들어줍니다.

사용 코드 보기

더보기
import React, { useRef, useState } from 'react';
import UserList from './UserList';
import CreateUser from './CreateUser';

function App() {
  const [inputs, setInputs] = useState({
    username: '',
    email: ''
  });
  const { username, email } = inputs;
  const onChange = e => {
    const { name, value } = e.target;
    setInputs({
      ...inputs,
      [name]: value
    });
  };
  const [users, setUsers] = useState([
    {
      id: 1,
      username: 'velopert',
      email: 'public.velopert@gmail.com'
    },
    {
      id: 2,
      username: 'tester',
      email: 'tester@example.com'
    },
    {
      id: 3,
      username: 'liz',
      email: 'liz@example.com'
    }
  ]);

  const nextId = useRef(4);
  const onCreate = () => {
    const user = {
      id: nextId.current,
      username,
      email
    };
    setUsers(users.concat(user));

    setInputs({
      username: '',
      email: ''
    });
    nextId.current += 1;
  };
  return (
    <>
      <CreateUser
        username={username}
        email={email}
        onChange={onChange}
        onCreate={onCreate}
      />
      <UserList users={users} />
    </>
  );
}

export default App;

배열에 새 항목을 추가 할 때에는 이렇게 spread 연산자를 사용하거나, concat 을 사용하시면 됩니다.

 

 

 

 

https://react.vlpt.us/basic/13-array-insert.html

 

13. 배열에 항목 추가하기 · GitBook

13. 배열에 항목 추가하기 이 섹션에서 사용된 코드는 다음 페이지에서 확인 할 수 있습니다. 이번에는 배열에 새로운 항목을 추가하는 방법을 알아보겠습니다. 우선, input 두개와 button 하나로 이루어진 CreateUser.js 라는 컴포넌트를 src 디렉터리에 만들어봅시다. CreateUser.js import React from 'react'; function CreateUser({ username, email, onChange, onCreat

react.vlpt.us