Skip to content

Instantly share code, notes, and snippets.

@kjessec
Last active February 8, 2019 04:03
Show Gist options
  • Save kjessec/dfcffdbadfddb359bdd155942c42732e to your computer and use it in GitHub Desktop.
Save kjessec/dfcffdbadfddb359bdd155942c42732e to your computer and use it in GitHub Desktop.
React 1일차 코드 잘 모르는 부분
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
const data = [
{ title: 'Hello World', content: 'Hello 1234', writer: 'JESSE'},
{ title: 'Hello World1', content: 'Hello 1asdf234'},
{ title: 'Hello World2', content: 'Helasdflo 1234'},
{ title: 'Hello World3', content: 'Heladsflo 1234'},
{ title: 'Hello World4', content: 'Helasdblo 1234'},
{ title: 'Hello World5', content: 'Helsaeflo 1234'},
]
class App extends Component {
// Q1. constructor, React에서 생성자는 (C++ 와 달리) class 이름이 아닌 constucgtor라는 함수를 명시적으로 사용하는것인지..?
// ==> 맞습니다~ 생성자 이름 규정은 언어마다 조금씩 다르기도 합니다
// 더불어서 JavaScript에서의 Class는 C++나 Java의 구현과는 조금 다릅니다. (prototypal inheritance)
// 자세한건 여기 --> https://medium.com/javascript-scene/master-the-javascript-interview-what-s-the-difference-between-class-prototypal-inheritance-e4cd0a7562e9
// Q2. super(props)를 부르는 이유는?
// ==> 2가지 이유가 있는데요. 첫번째는..
// 1) JavaScript class는 어떤 class가 자식 class이고 constructor를 별도로 정의하고 있다면
// super() (부모 class의 생성자)를 실행시켜 주지 않으면
// constructor에서 this 키워드를 사용할 수 없습니다.
// 이 예제에서의 App class는 React.Component를 상속하고 있고,
// 아래 예제에서는 this에 이것저것 많은걸 했기 때문에 super를 불러줘야 합니다.
// (상속을 받지 않는 class라면 super()는 안 불러도 됩니다.)
// 왜 그런지는.. JavaScript class는 사실 class가 아니기 때문입니다. 위 1번 질문 답변과도 관련이 있어요
// 2) 즉 this를 사용하기 위해서 super()를 해 줘야 하는건 알겠는데, 왜 super(props)냐??
// React.Component의 생성자는 this.props = props를 수행합니다.
// 즉 인자로 받는 props를 this.props로 assign하게끔 되어 있는데.. (다른 메서드에서도 접근할 수 있어야 하니까요)
// JavaScript class의 한계로 우리의 App 인스턴스는 props를 생성자에서 받을 수 있지만
// React.Component의 생성자까지 전달 시키려면 super(props)라는 방법을 사용해야만 합니다.
// (만약 우리의 컴포넌트가 props를 전혀 사용하지 않는다면 super()만 해도 무관합니다.^^)
// https://reactjs.org/docs/react-component.html#constructor
constructor(props) {
super(props)
// state 변수 선언, {}로 object로 초기화
this.state = { myVisitCounter: 0 }
// Q3. 아래 bind는 왜 하는것인가? 함수를 밖에 정의하기위해서??
// 만약 bind 하지 않으면, reset 버튼 클릭시 TypeError: Cannot read property 'setState' of undefined 발생
// ==> 이건 다음시간에 설명드리려고 했는데, JavaScript의 컨텍스트 문제입니다.
// 따로 gist를 만들어서 링크 걸어드릴께요~~
this.addVisitCounter = this.addVisitCounter.bind(this)
this.reset = this.reset.bind(this)
}
addVisitCounter() {
this.setState({ myVisitCounter: this.state.myVisitCounter+1 })
}
reset() {
this.setState({ myVisitCounter: 0 })
}
render() {
// Q4. 실제로 data 안에 값들이 여러개 병렬로 불리는 부분인데.. id는 없어도 되는지?
// ==> id라는 attribute는 HTML에서만 의미가 있고 React에서는 아무 의미가 없습니다
// 즉 안 해도 됩니다. 아래 라인 114에서 IconListRender를 실제로 렌더링할 때
// key라는 prop을 주고 있는데, 요건 필요합니다. (https://reactjs.org/docs/lists-and-keys.html#keys)
// key는 리액트에서 여러개의 자식노드들의 변경을 구분하기 위해서 필요한 prop입니다
// Array에 대한 렌더를 할 때 주로 사용되는데요.. 위 문서 한번 읽어보시죠
const IconListRender = ({ writer, title, content, onClick }) => (
<div onClick={onClick}>
<p>{writer}</p>
<code>{title}</code>
<p>{content}</p>
<hr/>
</div>
)
// Q5. constructor에서 state 변수로 초기화 했는데.. 여기 this.state를 해주는 이유가 뭐임?
// 안해주면 아래와 같이 onClick에서 no-undef 발생함
// Line 69: 'myVisitCounter' is not defined no-undef
// ==> 여기서 this.state는 초기화가 아니고 this.state에서 myVisitCounter를 접근하는 내용입니다
// const myVisitCounter = this.state.myVisitCounter 랑 같은 말입니다
// (javascript destructuring 문법: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
const { myVisitCounter } = this.state
return (
<div>
<h1>My Visit Counter: {this.state.myVisitCounter}</h1>
<button onClick={this.reset}>
Reset my counter
</button>
<MyBoard
onClick={() => this.addVisitCounter()}
boardId={() => Math.random()}
data={data}
visit={myVisitCounter}
ListRender={IconListRender}
/>
</div>
);
}
}
function MyBoard(props) {
const { boardId, data, ListRender, onClick, myVisitCounter } = props
// 각각의 그리는데..
// Q6. 여기서는 div id를 왜 사용할가?
// ==> 예제로 만든것이고 별로 의미는 없습니다. 허헛
return (
<div id={boardId()}>
<h1>{boardId()}: {myVisitCounter}</h1>
<input type="text"/>
{data.map(function(entry, entryIdx) {
return <ListRender
writer={entry.writer}
title={entry.title}
content={entry.content}
key={entryIdx}
onClick={onClick}
/>
})
}
</div>
)
}
// default
export default App;
@kjessec
Copy link
Author

kjessec commented Feb 8, 2019

일찍좀 올리세요

ㅠㅠ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment