React

Update, Delete 기능 구현

heeyeonjeong 2020. 10. 28. 19:22
반응형

CRUD

= Create Read Update Delete

 

update는 read기능과 create기능이 결합되어있다고 볼 수 있다.

 

- 기존 컨텐츠를 불러와서 form에 추가작업 할 것

- form기능이 이미 구현되어있는 컨텐츠에서 실행할 것

 

 Update 

 

state값을 form과 동기화시켜서 state값을 계속 변화시키기

 

//Components/UpdateContent.js
import React, { Component } from 'react';

class UpdateContent extends Component{
    constructor(props){ //가변적 데이터로 동작할 수 있게 -> state화 시켜주기
        super(props);
        this.state = {
            title:this.props.data.title, 
            desc:this.props.data.desc
        }
        this.inputFormHandler = this.inputFormHandler.bind(this) //refactoring
    } 
    inputFormHandler(e){ //refactoring
        this.setState({[e.target.name]:e.target.value})
    }
    render(){
      return(
        <article>
          <h2>Update</h2>
          <form action="/create_process" method="post" onSubmit={function(e){
            e.preventDefault();
            this.props.onSubmit(
              e.target.title.value,
              e.target.desc.value
            );
          }.bind(this)}>
          <p>
	      <input type="text" name="title" placeholder="title" value={this.state.title} onChange={this.inputFormHandler}></input>
          </p>
          <p>
              <textarea name="desc" placeholder="descripstion" value={this.state.desc} onChange={this.inputFormHandler}></textarea>
          </p>
          <p>
              <input type="submit"></input>
          </p>
          </form>
        </article>
      )
    }
  }
  

export default UpdateContent;

 

- read only인 props의 값을 그대로 가져오면 value값을 바꿀 수 없다

- value값으로 component안에서 가변적인 데이터= state화 시켜준다

- but, 여전히 수정은 불가 input의 값을 바꿨을때, state값을 바뀌게 해야지만 read only 상태가 아니게됨

- onChange( )를 꼭 사용해야 한다 but, 입력이 한글자씩만 된다

- 한글자씩 바뀌는 것을 바로바로 state에 동기화 시키기, setState

 

 

//App.js - getContent() 내에서 실행
}else if(this.state.mode === 'Update'){
  let _content = this.getReadContent();
  _article = <UpdateContent data={_content} onSubmit={function(_id, _title, _desc){
    let _contents = Array.from(this.state.contents);
    let i = 0;
    while(i < _contents.length){
      if(_contents[i].id === _id){
        _contents[i] = {id:_id, title:_title, desc:_desc};
        break;
      }
      i = i+1;
    }
    this.setState({
      contents: _contents,
      mode: 'read'
    });
  }.bind(this)}></UpdateContent>
};

 

 

 Delete 

 

//App.js - render 내에서 실행
<Control onChangeMode={function(_mode){
  if(_mode === 'Delete'){
    //delete 기능
    if(window.confirm('really?')){
      let i=0;
      let _contents = Array.from(this.state.contents);
      while(i < _contents.length){
        if(_contents[i].id === this.state.selected_content_id){
          _contents.splice(i,1);
          break;
        }
        i = i+1;
      }
      this.setState({mode:'welcome', contents: _contents});
      alert('deleted!');
    }            
  }else{
    this.setState({mode:_mode});
  }
}.bind(this)}></Control>

 

- delete기능이 있는 위치 찾고, 호출하고 있는 props 찾아가기

- mode가 delete일때 삭제기능 구현하기

- 정말 삭제할 것 인지 한번더 물어보는 기능 구현하기 → window.confirm( ) = true면 삭제

- splice 사용하기

(- alert으로 삭제했다고 경고창 띄어주기!)

 

 

CRUD

 


+)

 

immutable

- 불변으로 번역됨

- 구현을 단순하게 유지해서 높은 복잡성에 도전하기 위한 노력   너무 가변적인 변경 가능성은 좋지 않다.

- 의도하지 않은 값의 변경은 난감한 이슈. 객체를 immutable하게 다루기 위한 라이브러리가 있다.

immutable 사이트 -  이 라이브러리는 배열, 객체의 대체제로 사용할 수 있다. 모든 연산이 원본을 변경하지 않고 복제된 원본을 변경한 결과를 return한다. 이런 도구를 사용하면 더욱 견고한 애플리케이션을 만드는데 도움이 된다

 

router

- react router사용 url에 따라서 적당한 component가 나오게 할 수 있다.  npm을 통해 설치해서 사용할 수 있는 플러그인과 같은 기능이다.

 

create-react-app

- 더 복잡한 작업에서는 기본도구로 부족하다고 생각할 수있다

npm run eject을 사용해서 마음대로 개발환경을 수정할 수 있다. but, 한번 eject을 하면 다시 돌아갈 수 없다

 

redux

-  react component가 많아지면 component간의 교류가 굉장히 까다로워진다. 부모가 자식으로 데이터를 전달할 때는 props를 따라가야하고, 자식이 부모를 찾아갈 떄는 이벤트를 버블링 시켜야 한다. 만약 component가 많이 중첩되어있다고 생각했을때, 이런상황에서 redux가 유용하다

- redux라는 중앙에 데이터 저장소를 만들고 모든 component는 중앙의 저장소 redux와 직접 연결된다.

- 저장소의 데이터가 변경되면 모든 component가 영향을 받아서 변화를 하게 된다. 

 

react server side rendering

- 서버쪽에서 웹을 완성한 후, 클라이언트에 완성된 html을 전송하는 것으로 애플리케이션 구동을 시작할 수 있다.

- 구동시간을 단축할 수 있다. 

 

react native

- react와 같은 방법으로 네이티브 앱을 만들수 있다. (네이티브앱이란? Android, iOS와 같은 플랫폼을 의미한다.)

- 하나의 코드로 모든 플랫폼을 동작하는 애플리케이션을 만들 수 있다.