Javascript
useState 배열값중 n번째값 바꾸기
don_Kim
2021. 2. 18. 15:23
function App() {
const [postTitle, setPostTitleState] = useState([
'men jacket',
'good jean',
'fancy shirt',
]);
function changeTitle() {
/*
1. postTitle이라는 state는 직접 수정할 수 없기때문에 복사본을만든다
2. 새로운 변수에 복사할때는 spread 연산자를 사용해서 shallow/deep카피 한다
- 등호(=)를 이용해서 array나 object를 복사하면 별개의 자료형이 만들어지지않고 값을 공유한다고함
- https://www.samanthaming.com/tidbits/35-es6-way-to-clone-an-array/ 참조
*/
let newTitleArray = [...postTitle];
newTitleArray[0] = 'women coat';
setPostTitleState(newTitleArray);
}
return (
<div className="App">
<div className="black-nav">LOGO</div>
<div className="section">
<div className="posts">
<h3>
{postTitle[0]}
</h3>
<p>Description</p>
<p>Date</p>
<button onClick={changeTitle}>click</button>
<div className="border"></div>
</div>
<div className="posts">
<h3>
{postTitle[1]}
</h3>
<p>Description</p>
<p>Date</p>
<button onClick={changeTitle}>click</button>
<div className="border"></div>
</div>
<div className="posts">
<h3>
{postTitle[2]}
</h3>
<p>Description</p>
<p>Date</p>
<button onClick={changeTitle}>click</button>
<div className="border"></div>
</div>
</div>
</div>
);
}
export default App;
www.samanthaming.com/tidbits/35-es6-way-to-clone-an-array/
ES6 Way to Clone an Array 🐑 | SamanthaMing.com
When we need to copy an array, we often time used `slice`. But with ES6, you can also use the spread operator to duplicate an array...
www.samanthaming.com
쉽게 설명되어있네요