컴포넌트 실습 (Feat.map)

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
31
32
33
34
35
36
37
38
39
import React from 'react';
import './App.css';

// JSX -> HTML 태그
// JSX -> style을 통해 css (JSX)
// JSX -> className을 통해 css (css -> App.css)

function WorldClock(props){
return(
<div className={"WorldClock"}>
<h2> 도시 : {props.city} </h2>
<p> 시간 : {props.time} 시</p>
</div>
);
}

function App() {
//list 타입의 Data
const cityTimeData= [
['서울', 10],
['북한', 11],
['도쿄', 12],
['베이징', 1],
]

const WorldClockList = cityTimeData.map((citytime, index)=>
<WorldClock city={citytime[0]} time ={citytime[1]} key ={index} />
)
return (
<div className="App">
<h1 className = {'myStyle'}>안녕하세요</h1>
<div className= {'post'}>첫 게시글입니다.</div>
{WorldClockList}
</div>
);
}

//컴포넌트 수출
export default App;

오류

index.js:1375 Warning: Each child in a list should have a unique “key” prop.

1
2
3
-> const WorldClockList = cityTimeData.map((citytime, index)=>
<WorldClock city={citytime[0]} time ={citytime[1]} key ={index} />
)

State

Props만으로도 표현 불가능 / Render로 표시 불가능 -> State 사용

state stateless
function O(hook기술) O
Class O O

State는 좋지만 무겁고 어렵기 때문에 되도록 사용안함

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
// 요구사항 1. 시간과 분이 변화하는 것을 보고 싶다.
// 요구사항 2. 동적으로 보고싶다.
class WorldClock extends React.Component {
constructor(props){
super(props)
this.state = {
hour: this.props.time,
minute : 0
}
// this.setState
// this.state.minute += 1; -> 절대 불가
setInterval(()=>{
this.setState((state)=>(
state.minute === 59
?{hour: state.hour + 1, minute :0}
: {minute: state.minute + 1}
))
}, 100)
}
// render 미리 약속되있는 함수
render(){
return(
<div className={"WorldClock"}>
<h2> 도시 : {this.props.city} </h2>
<p> 시간 : {this.state.hour}시 {this.state.minute}분</p>
</div>
)
}
}

실행 결과

State

하루를 기록하다