update 구현 [3] - state 변경

SPANKEEE·2023년 3월 28일
0

리액트-시작

목록 보기
29/30

이전 챕터에서 props로 들어온 데이터를 state 로 만들고 state 값을 각가의 폼과 동기화시켜서 state 의 값을 계속해서 변화시키는 방법을 살펴보았다.

이렇게 업데이트를 하려면 어디를 업데이트 할 것인지에 대한 식별자가 필요하다.

식별자에 대해서 이해하고 upadatestate 값을 변경해보자.


식별자

업데이트를 할 대 어디를 업데이트 할 것인지에 대한 식별자가 필요하다.

form 에서 수정할 때 id 와 같이 사용자한테 보일 필요가 없는 데이터는 hidden form 에 작성한다.

  • UpadateArti.js
// state에 id 추가
this.state = {
  id : this.props.data.id,
  ...
}
// * hidden form : <form> 안에 *hidden form 추가
<input type="hidden" name ="id" value ={this.state.id}></input>

<hidden form> 은 존재하지만 눈에 보이지 않는다.

그 다음에 submit 버튼을 눌러서 onSubmit 이벤트가 발생할 때 이 컴퍼넌트로 들어온 onSubmit props 를 실행한다.

이 때 id 값을 추가한다.

this.props.onSubmit(
	this.state.id,
    this.state.title,
    this.state.desc
);

e.target.title.valuee.target.desc.valuestate 와 동기화 되기 때문에 위 코드로 바꿔주었다.

수정을 하기 위해서 contents 를 복제를 해보자.

복제(데이터)

자바스크립트는 Array.from() 기능을 갖고 있다.

var _contents = Array.from(this.staete.contents);

이렇게 코드를 작성하면 this.state.contents 라고 하는 원본을 복사한 새로운 _contents 라는 이름의 배열을 만들게 된다.

그 다음 _contents 안에 있는 원소들을 확인하여 id 값이 우리가 수정하고자 하는 것과 같은 원소를 찾아야 한다.

  • App.js > else if(this.state.mode === update) 구간
else if (this.state.mode === 'update') {
  _content = this.getReadContent();
  _article = <UpdateArti data={_content} onSubmit={
    function(_id, _title, _desc){
      var _contents = Array.from(this.state.contents);
	  var i = 0;
      while (i < _contents.length) {
        if (_contents[i].id === _id) {
          _contents[i] = { id: _id, title: _title, desc: _desc };
          break;
        }
        i = i + 1;
      }
// ... 아래 내용 추가

contentsid 값과 입력받은 id 값이 같다면 그 객체를 교체해주도록 작성한다.

교체를 하면 더 반복문을 할 필요가 없기 때문에 break 문을 이용해 빠져나온다.

  • App.js > else if(this.state.mode === update) 구간
else if (this.state.mode === 'update') {
  _content = this.getReadContent();
  _article = <UpdateArti data={_content} onSubmit={
    function(_id, _title, _desc){
      var _contents = Array.from(this.state.contents);
	  var i = 0;
      while (i < _contents.length) {
        if (_contents[i].id === _id) {
          _contents[i] = { id: _id, title: _title, desc: _desc };
          break;
        }
        i = i + 1;
      }
      // setState
      this.setState({
        contents : _contents
      });

이렇게 교체한 _contents 를 입력 값으로 주어진다.

웹 브라우저를 통해 잘 수정되는 거슬 확인할 수 있다.


이전에 오리지널 contents 를 직접 수정하지 않고 contents 를 복제해서 새로운 배열을 만들었다.

이것이 불변이라는 특성이고, 원본을 바꾸지 않는 테크닉이다.

이 테크닉은 차후 성능을 튜닝할 때 필요하다.


배열이나 객체를 수정할 때는 원본을 복제하고 복제한 것을 수정해서 복제본을 넣도록 concat영역도 다시 바꿔보자.

  • App.js > else if(this.state.mode === create) 영역
var _content = Array.from(this.state.contents);
_content.push({
  id:this.max_content_id,
  title:_title,
  desc:_desc
});
this.setState({
  contents:_contents
});

마지막으로 어떤 컨텐츠를 선택하고 업데이트를 활성화하여 내용을 수정하고 submit할 때 바뀐 내용을 바로 보고싶다 이럴땐 --> mode : read 로 바꾸면 된다.

즉 state의 mode를 바꿔주도록 코드를 추가한다.

// update 영역
this.setState({
  contents:_contents,
  mode:'read'
)};

이제 update를 누르고 내용을 바꾼 뒤 submit 버튼을 누르면 내용과 본문이 모두 바뀌게 된다.

create도 마찬가지로 내용을 추가하면 mode를 read로 바꾸고 selected_content_id 를 지금 추가한 값으로 바꿔준다.

// create 영역
this.setState({
  contents:_contents,
  mode:'read',
  selected_content_id:this.max_content_id
});

이제 create 하면 내용이 추가되고, 추가된 본문 내용이 화면에 출력되는 것을 확인할 수 있다.

profile
해야되요

0개의 댓글