[생활코딩 React] ⑥ Update & Delete 기능 구현

Glenn·2019년 11월 19일
0

[생활코딩]React

목록 보기
6/6

🎥 생활코딩 YouTube

1. Update 구현

" Nav Update 클릭 👉 contents 영역 : 해당 form 으로 변경 👉 내용 변경 후 button 클릭 시 변경 "

  • CreateContent.js를 복사하여 UpdateContent.js 생성

1) form

" TOC.js내의 카테고리를 선택한 뒤 update 클릭 시 update Form 내의 내용을 선택한 내용으로 출력하자 "
🔗 Forms - React

//App.js

import React, { Component } from 'react';
import './App.css';
import ReadContent from "./components/ReadContent";
import CreateContent from "./components/CreateContent";
import UpdateContent from "./components/UpdateContent";
import TOC from "./components/TOC";
import Subject from "./components/Subject";
import Control from "./components/Control";

class App extends Component {
  constructor(props) { //props, state의 값이 변경되면 화면이 다시 그려진다.
    super(props);
    this.max_content_id = 3;
    this.state = {
      mode: "create",
      selected_content_id: 2, // 임의로 설정
      Subject: { title: 'WEB', sub: 'World Wide Web!' },
      welcome: { title: 'Welcome', desc: 'Hello, React!!' },
      contents: [
        { id: 1, title: 'HTML', desc: 'HTML is information' },
        { id: 2, title: 'CSS', desc: 'Css is for design' },
        { id: 3, title: 'JavaScript', desc: 'JavaScript is for interactivs' }
      ]
    }
  }
  getReadContent() { // 선택한 카테고리의 내용을 가져오는 function
    var i = 0;
    while (i < this.state.contents.length) {
      var data = this.state.contents[i];
      if (data.id == this.state.selected_content_id) {
        console.log(data);
        return data;
        break;
      }
      i += 1;
    }
  }

  getContent() {
    var _title, _desc, _article = null;
    if (this.state.mode === 'welcome') {
      _title = this.state.welcome.title;
      _desc = this.state.welcome.desc;
      _article = <ReadContent title={_title} desc={_desc}></ReadContent>;
    } else if (this.state.mode === 'read') {
      var _content = this.getReadContent(); // function 사용
      _article = <ReadContent title={_content.title} desc={_content.desc}></ReadContent>;
    } else if (this.state.mode === 'create') {
      _article = <CreateContent onSubmit={function (_title, _desc) {
        this.max_content_id += 1;
        var newContents = Array.from(this.state.contents);
        newContents.push(
          { id: this.max_content_id, title: _title, desc: _desc }
        );
        this.setState({
          contents: newContents
        });
      }.bind(this)}></CreateContent>;

		//*** UPDATE 구역 ***//
		//내용은 아직 기존의 create와 동일함

    } else if (this.state.mode === 'update') {
      _content=this.getReadContent();
      _article = <UpdateContent data={_content} onSubmit={function (_title, _desc) {
        this.max_content_id += 1;
        var newContents = Array.from(this.state.contents);
        newContents.push(
          { id: this.max_content_id, title: _title, desc: _desc }
        );
        this.setState({
          contents: newContents
        });
      }.bind(this)}></UpdateContent>;
    }
    return _article;
  }
		//*** UPDATE 구역 ***//

  render() { //어떤 HTML을 그릴것인가를 결정하는 함수
    return (
      <div className="App">
        <Subject
          title={this.state.Subject.title}
          sub={this.state.Subject.sub}
          onChangePage={function () {
            this.setState({ mode: 'welcome' });
          }.bind(this)}>
        </Subject>
        <TOC onChangePage={function (id) {
          this.setState({
            mode: 'read',
            selected_content_id: Number(id)
          });
        }.bind(this)}
          data={this.state.contents}></TOC>
        <Control onChangeMode={function (_mode) { //이벤트 핸들러 설치
          this.setState({ mode: _mode });
        }.bind(this)}></Control>
        {this.getContent()}
      </div>
    );
  }
}

export default App;
//UpdateContent.js

import React, { Component } from 'react';

class UpdateContent extends Component {
  constructor(props) {
    super(props);
    this.state = {
        title:this.props.data.title,
        desc:this.props.data.desc
    }
    this.inputForHandler=this.inputForHandler.bind(this);
  }
  inputForHandler(e){
    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.inputForHandler}></input>
						 // React의 input은 value를 설정할 경우 변경이 안되므로 onChange 함수를 사용하여
						 // 변경된 내용을 즉각적으로 value에 입력하여야 한다. 
						 // 이와 같은 기능을 inputforHandler로 정의
          </p>
          <p>
            <textarea 
            name="desc" 
            placeholder="description"
            value={this.state.desc}
            onChange={this.inputForHandler}></textarea>
          </p>
          <p>
            <input type="submit" value="submit"></input>
          </p>
        </form>
      </article>
    );
  }
}

export default UpdateContent;

2) state 변경

} else if (this.state.mode === 'update') {
      _content = this.getReadContent();
      _article = <UpdateContent 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) { // 받아온 id와 일치하는 content의 내용을 변경
              _contents[i] = { id: _id, title: _title, desc: _desc }
              break;
            }
            i = i + 1;
          }
          this.setState({ // 변경한 contents를 설정, read로 이동
            contents: _contents,
            mode: 'read'
          });
        }.bind(this)}></UpdateContent>;
    }

2. Delete 구현

<Control onChangeMode={function (_mode) { //이벤트 핸들러 설치
          if(_mode==="delete"){
            if(window.confirm('Really ?!')){
              var _contents=Array.from(this.state.contents);
              var i=0;
              while(i<_contents.length){
                if(_contents[i].id===this.state.selected_content_id){
                  _contents.splice(i,1); //slice를 사용하여 i번째부터 1개의 배열 삭제
                  break;
                }
                i+=1;
              }
              this.setState({ //삭제한 contents를 세팅하고 mode를 welcome으로 변경
                mode:'welcome',
                contents:_contents
              });
              alert('deleted');
            }
          }else{
            this.setState({ mode: _mode });
          }
        }.bind(this)}></Control>
profile
Front-end developer

2개의 댓글

comment-user-thumbnail
2019년 11월 19일

getReadContent 에서 i 에 대한 증감은 i++ 로 증감 연산자를 사용해 표기할 수 있어요.
https://codeburst.io/javascript-increment-and-decrement-8c223858d5ed

1개의 답글