Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- node
- 제로초예제
- sequelize
- React
- 시퀄라이즈
- 클래스컴포넌트
- mongo
- NPM
- NoSQL
- 리액트컴포넌트
- 리액트스타디
- 리액트
- component
- 리액트기초
- MongoDB
- express-generator
- nodejs교과서
- sementicversion
- React Component
- npm명령어
- 시퀄라이즈공부
- nodeJS
- mongoose
Archives
- Today
- Total
개발노트
11. react life cycle 본문
리액트의 라이프 사이클
render 함수가 실행되면
DOM에 (render)함수를 붙여주는데 붙여주고난 그 순간에
이벤트잡아서 원하는 설정이 가능함 그게 componentDidMount,
컴포넌트가 첫 렌더링 된 후
componentDidMount
-비동기 요청
컴포넌트가 제거되기 직전
componentWillUnmount
(부모컴포넌트가 자식컴포넌트 없앴을때 자식이컴포넌트가 없어지기(unmount)전에 실행됨)
리렌더링후에 실행
componentDidUpdate
-비동기 요청의 삭제 (컴포넌트를 삭제해도 만약 setInterval을 걸었을 경우 계속실행됨)
클래스컴포넌트
constructor state부분
render
(ref)
componentDidMount
setState/부모가props바꿀때 -> (shouldComponentUpdate)T -> re render -> componentDidUpdate
부모가 자식없앨때 -> componentWillUnmount -> 소멸
import React, { Component } from 'react';
const rpsCoords = {
rock:'0px',
scissor: '-142px',
paper: '-284px',
};
const score = {
scissor: 1, //가위
rock:0, //바위
paper:-1 //보
}
//컴퓨터가 어떤손 내는지 판단
const computerChoice = (imgLocation)=>{
return Object.entries(rpsCoords).find( function(v){
return v[1] === imgLocation;
})[0];
}
class RPS extends Component {
state = {
result:'',
imgLocation:0,
score:0,
}
interval;
componentDidMount(){ //첫렌더링 된후
//이미지 위치값을 묵 으로
//인터발을 걸어주는데 안에 화살표함수에서 img위치가 rsp위치의 묵과 같다면
// 상태값의 이미지위치를 가위로
this.setState( {imgLocation: rpsCoords.rock });
this.changeHand();
}
componentWillUnmount(){ // 제거직전
}
componentDidUpdate(){ //리렌더링된후 실행
}
changeHand = ()=>{
this.interval = setInterval( ()=>{
const { imgLocation } = this.state;
if( imgLocation == rpsCoords.rock ){
this.setState({ imgLocation: rpsCoords.scissor })
}else if( imgLocation == rpsCoords.scissor ){
this.setState({ imgLocation: rpsCoords.paper })
}else{
this.setState({ imgLocation: rpsCoords.rock })
}
}, 500 );
}
//사용자가 가위바위보 선택했을때
onClickBtn = ( userChoose )=>{
clearInterval( this.interval );
const { imgLocation } = this.state;
const userScore = score[userChoose]; //siccer 1
const comScore = score[computerChoice(imgLocation)]; //paper -1
const diff = userScore - comScore; //결과
if(diff === 0){ //
console.log( 'again');
this.setState({
result:'again',
})
}else if( [-1, 2].includes(diff) ){ //이겼음
console.log( 'win');
this.setState( (prevState)=>{
return {
result:'win !',
score: prevState.score + 1,
}
});
}else{ //졌다
console.log('loose');
this.setState( (prevState)=>{
return {
result:'lose',
score: prevState.score - 1,
}
});
}
clearInterval(this.interval);
setTimeout( ( )=>{ this.changeHand() }, 2000 );
}
render(){
const { result, score, imgLocation } = this.state;
return(
<>
<div id="computer" style={{ background: `url(https://en.pimg.jp/023/182/267/1/23182267.jpg) ${imgLocation} 0` }} />
<ul>
<li id="scissor" className="btn" onClick={ ()=>{this.onClickBtn('scissor')} }> 가위</li>
<li id="rock" className="btn" onClick={ ()=>{this.onClickBtn('rock')} }> 바위</li>
<li id="paper" className="btn" onClick={ ()=>{this.onClickBtn('paper')} }> 보</li>
</ul>
<p>{result}</p>
<p>현재 {score}점</p>
</>
)
}
}
export default RPS;
<html lang="ko">
<head>
<meta charset="utf-8">
<title>game</title>
</head>
<style>
#computer {
width: 142px;
height: 200px;
background-position: 0 0;
outline: 5px solid gold;
}
ul{width:100%; padding:0; height:180px;}
li{ width: 142px; height:180px; outline:1px solid grey; float:left; list-style:none; }
li{
background: url(https://en.pimg.jp/023/182/267/1/23182267.jpg) 0px -11px;
}
li#scissor{
background-position: -142px -11px;
}
li#paper{
background-position: -284px -11px;
}
</style>
<body>
<div id="root"></div>
<script src="./dist/app.js">
</script>
</body>
</html>
methodFunction = () => () => {}
//<li id="scissor" className="btn" onClick={ ()=>{this.onClickBtn('scissor')} }> 가위</li>
<li id="scissor" className="btn" onClick={ {this.onClickBtn('scissor')} }> 가위</li>
//onClickBtn = ( userChoose )=> { }
onClickBtn = ( userChoose )=> () => { }
이런식으로 변경 가능.
인자가 들어갈수도 있다
'React > basic' 카테고리의 다른 글
12. componentDidUpdate , setInterval (0) | 2020.07.27 |
---|---|
11 (2)hooks / useEffect (0) | 2020.07.26 |
10. (4)jsx 에서 for, if (0) | 2020.07.26 |
10. (3) hooks / useState (0) | 2020.07.26 |
10. (2) ResponseCheck Game / setTimeout, if (0) | 2020.07.26 |