react- deep copy

BackEnd_Ash.log·2020년 7월 9일
0

react

목록 보기
18/41

full code

import React, { useState } from "react";
import "./App.css";

const App = () => {
  let posts = "고기 맛집";
  const [textTitle, setTextTitle] = useState([
    "남자코트 추천",
    "강남 우동맛집",
    "파이썬독학",
  ]);

  const [counter, setCounter] = useState(0);

  const titleChange = () => {
    // const change = textTitle; // 이거는 값 공유 이다 .
    const change = [...textTitle]; // deep copy 를 해야함
    change[0] = "여자코트 추천";
    setTextTitle(change);
  };

  const sequenceChange = () => {
    const change = [...textTitle];
    const re_change = change.sort();
    console.log(re_change);
    setTextTitle(re_change);
  };

  return (
    <div>
      <div className="App">
        <div className="black-nav">blog</div>
        <div>blog text</div>
      </div>
      <button onClick={titleChange}>title change button</button>
      <button onClick={sequenceChange}>sequence change button</button>
      <div className="list">
        <h3>
          {textTitle[0]} <span onClick={() => setCounter(counter + 1)}>👍</span>
          {counter}
        </h3>
        <p>2.17</p>
        <hr />
      </div>
    </div>
  );
};

export default App;

copy

const change = textTitle;

Actually this is not copying, it is sharing.
change is also same reference.

deep copy

  const change = [...textTitle]; [1] // deep copy 
    change[0] = "여자코트 추천";    [2]
    setTextTitle(change);        [3]
[1] :  Copy the entire copy.
[2] :  change index 0 text
[3] :  replace change 

sequence

if you want sequence apply , you have to sort() function

  const sequenceChange = () => {
    const change = [...textTitle];
    const re_change = change.sort();
    console.log(re_change);
    setTextTitle(re_change);
  };
profile
꾸준함이란 ... ?

0개의 댓글