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;
const change = textTitle;
Actually this is not copying, it is sharing.
change is also same reference.
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
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);
};