## 2021/01/05
<update 기능 구현 시 Check 해야 할 점>
UpdateContent.js
import React, { Component } from 'react';
class UpdateContent extends Component{
constructor(props){
// state화 시키기
super(props);
this.state={
id: this.props.data.id,
title : this.props.data.title,
desc : this.props.data.desc
}
this.inputFormHandler = this.inputFormHandler.bind(this);
}
inputFormHandler(e){
this.setState({[e.target.name]:e.target.value});
}
render(){
return(
<article>
<h2>Update</h2>
<form acrion="/create_process" method="post"
onSubmit={function(e){
e.preventDefault();
this.props.onSubmit(
this.state.id,
this.state.title,
this.state.desc
);
}.bind(this)}
>
<input type="hidden" name="id" value={this.state.id}></input>
<p>
<input
type="text"
name="title"
placeholder="title"
value={this.state.title}
// input이 바뀔 때마다 state가 바뀔 수 있도록
onChange={this.inputFormHandler}>
</input>
</p>
<p>
<textarea
name="desc"
placeholder="description"
value={this.state.desc}
// input이 바뀔 때마다 state가 바뀔 수 있도록
onChange={this.inputFormHandler}
></textarea>
</p>
<p>
<input type="submit"></input>
</p>
</form>
</article>
);
}
}
export default UpdateContent;
onChange = {this.inputFormHandler}
→ 이 코드의 경우 inputFormHandler함수를 render위에 선언함으로써 코드를 리팩토링 해 보기 쉽게 정리한 것이다.
App.js 일부
else if(this.state.mode === 'update'){
// 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){
_contents[i] = {id:_id, title:_title, desc:_desc};
break;
}
i = i + 1;
}
this.setState({
contents: _contents,
mode: 'read' //update가 끝난 후 모드를 변경한다
});
}.bind(this)}></UpdateContent>
}
return _article;
}
<delete 기능 구현 시 Check 해야 할 점>
App.js 일부
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); //발견한값부터 한개를 지운다
break;
}
i = i + 1;
}
this.setState({ //삭제 시
mode:'welcome',
contents: _contents
});
alert('deleted!!');
}
}else{ //삭제x
this.setState({
mode: _mode
});
}
}.bind(this)}></Control>
{this.getContent()}
{this.getContent()}
→ article을 원래 리턴 받았지만 article을 리턴받는 함수인 getContent를 만들어 this.getContent로 표기한 것이다.
selected_content_id
→ 읽기모드의 TOC.js에서 받아온 아이디를 숫자화 한 것