React JS 로 웹 서비스 만들기

SSO·2020년 2월 13일
0

Lectures and documents

목록 보기
1/2

강의: https://academy.nomadcoders.co/courses/216871

1. Requirement

node js, npm(yarn), npx, git
HTML, CSS, JS

2. Set up

1) create-react-app

npx create-react-app project_name

2) How react works

  • react는 JS를 html로 변환.
  • JS component를 html의 root element에서 실행.
  • React는 virtual document object model.
  • html 파일 안에는 root element만 있고, 나머지는 가상.
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>
<!--index.html-->
  • component란, html을 return하는 function.
  • ReactDom은 오직 1개의 component만(보통 App.js) render하기 때문에 나머지 component들은 App.js 내에서 렌더되어야 한다.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));
//index.js

3. JSX와 Props

1) JSX = JS + HTML

  • JSX에서는 HTML의 class대신 className사용. (html에서는 class로 해석)

2) props는 해당(자식) 컴포넌트에 전달하려는 정보.

  • react는 props를 해당 컴포넌트의 argument로 전달.
  • Props are arguments passed into React components.
function RedKiwi (props){
  return <p>You can learn {props.language} with Redkiwi.</p>;
}

function App (){
  return <RedKiwi language="English"/>;
}
  • 여기서 props는 { languages:"English" } 라는 Object.
// 위의 (props)와 여기의 ({language})는 동일.
function RedKiwi ({ language }){
  return <p>You can learn {language} with Redkiwi.</p>;
}

Dynamic component generation with map

(for dynamic data)

function RedKiwi (props){
  return <p>You can learn {props.language} with Redkiwi.</p>;
}

function App() {
  const languages = ["English", "Korean", "Japanese", "Chinese"];
 
  return languages.map(lang=> <RedKiwi key={lang} language={lang}/>);
}

👩🏻‍map을 사용하여 component를 rendering할 때는 key도 주어야 함. (react element의 key는 모두 unique해야하기 때문)

3) propTypes check: 여러가지 prop types 참고
원하는 props이 제대로 전달되었는지 확인하는 방법.

yarn add prop-types

4. State와 Component Life Cycle

1) State

  • The state object is where you store property values that belongs to the component.
  • dynamic data의 관리에 사용.

class component

  • react는 class component의 render method (알아서) 자동 실행.
  • react에서는 setState를 통해서 state가 갱신될 때에만 render함수가 재호출된다 => 따라서 state변화는 setState를 통해서만 가능.
  • react는 변화한 부분만 re-render한다.

setState

//setState
setState(updater[, callback])
//updater함수
(state, props) => stateChange
//setState
setState(stateChange[, callback])
//stateChange (updater함수 대신 객체 전달 가능)
{language:s"English"}
  • React는 state 변화가 즉시 적용되는 것을 보장하지 않음. (오히려 일괄갱신, 혹은 미뤄짐 가능)
    이로 인하여 setState()를 호출하자마자 this.state에 접근하는 것이 잠재적인 문제가 될 수 있음.
    => componentDidUpdate 또는 setState의 콜백(setState(updater, callback))을 통해 갱신이 적용된 뒤에 실행되는 것을 보장할 수 있음. 참고
//잘못된 방법
this.setState(language:this.state.language);
//올바른 방법
this.setState(state => language:state.language);
  • 초기선언 없이도 setState를 통해 state추가가 가능하지만, 초기 선언 권장.
class RedKiwi extends React.Component{
  constructor(props) {
    super(props);
    this.state = { language:"English" }; //초기선언
  }

  componentDidMount(){
    setTimeout(() => this.setState({ language:"Korean" }), 3000); // 3초후 language값 갱신
  }

 render() {
   return <p>Let's learn {this.state.language} with RedKiwi.</p>;
 }
}
  • everytime you call setState, React re-render with new State.

2) Life Cylce method 참고

5. Fetching data

yarn add axios

axios 사용시에 동기화를 위해 async- await 이용.

6. Github로 웹페이지 만들기

GitHub Pages are public web pages for users, organizations, and repositories, that are freely hosted on GitHub's github.io domain or on a custom domain name of your choice. ... Your site is automatically generated by GitHub Pages when you push your source files.

Github Pages

Github에서 무료로 호스팅을 제공하는 공개 웹페이지
(호스팅이란 서버의 전체 혹은 일부를 이용할 수 있도록 임대해 주는 서비스)

1) user or organization page

repogitory[username].github.io 라는 이름으로 프로젝트를 생성하면, master 브랜치에 업로드 하는 것으로 바로 배포(page 생성).

2) project page

gh-pages
사용자가 만든 웹페이지를 깃허브의 github.io 도메인이나 사용자가 요청한 도메인 이름으로 제공하는 서비스를 이용하기 위해 github에 source를 업로드 하도록 하는 모듈
gh-pages 브랜치로 푸시하면 해당 브랜치 소스가 자동으로 github page로써 배포.
gh-pages branch on the GitHub Repository is where the source code is hosted.

웹페이지 주소(project URL)

https://[username].github.io/[projectName]

React App 호스팅하기

gh-pages 설치

yarn add gh-pages

package.json 수정
프로덕션 빌드를 생성하고 githube page에 배포하기 위한 script 추가

"homepage":"https://[username].github.io/[projectName]"
"deploy":"yarn run build && gh-pages -d build"

#deploy script는 deploy와 predeploy로 나눠서 작성도 가능

"deploy":"gh-pages -d build"
"predeploy":"yarn run build"

deploy

yarn run deploy

deploy까지 완료되면 publish 될 것.

SPA React App 호스팅하기

깃허브는 SPA를 지원하지 않기 때문에, 이를 위한 별도의 과정이 필요.

https://iamsjy17.github.io/react/2018/11/04/githubpage-SPA.html

http://spa-github-pages.rafrex.com/
https://github.com/sujinleeme/spa-github-pages-ko

7. Router 만들기

위에 SPA React App 호스팅 하기 항목이 있기는 한데, 이 수업자체가 SPA만들기라서 Router로 Navigation 만들때 SPA로 만드는 방법을 알려주고 있음. => HashRouter + Link to 이용하기

profile
happy

0개의 댓글