본문 바로가기

React

setup / props / state / data fetch

반응형

| NomardCorder

react setup

react app 만들기

react app 파일 열기, github 업로드

window+r 로 cmd창 열기

cd documents로 documents 이동 → code movie-app/ 명령어 작성으로 vscode폴더 열기

 

readme 간단히 작성 후,

 

package.json에서 test, eject는 신경쓰지 않는다(삭제) + 등등 필요없는 파일 삭제

 

github에 업로드

 

+용어 ) pubilc의 favicon = 웹 탭의 상단에 보이는 아이콘


 

How does React work?

애플리케이션이 화면을 로드할 때, 빈 html을 로드하게 되고, react가 component에 작성해둔것을 html에 밀어넣게 된다.

-> 소스코드가 보이지 않음 -> virtual이고, 존재하지 않기 때문에 react가 빠른 이유이다.  

 

react JSX & PROPS

- component는 html을 반환하는 함수이다.

- react는 component를 사용해서 html처럼 작성하려는 경우에 필요하다.

  -> js와 html사이의 이러한 조합을 jsx라고 부른다. js안의 html을 jsx라고 부른다

- react application은 한번에 하나의 component만 rendering할 수 있다. = <App/>

  -> 따라서 모든 것 은 application안에 들어가야한다

 

 

//App.js
import React from 'react';

function Food({fav}) { //props.fav = {fav}
  return (
    <h2>i love {fav}</h2> //{props.fav} = {fav}
  );
}

function App() {
  return (
    <div>
      <h1>hello</h1>
      <Food fav = "coffee"/>
      <Food fav = "jiyeon"/>
    </div>
  );
}

export default App;

 

- props.key = {key}

 

 

import React from 'react';

function Food({name, desc}) {
  return (
    <div>
      <h1>i love {name}</h1>
      <p>this color is {desc}</p>
    </div>
  );
}

const FoodLike = [
  {id:1, name:"coffee", desc:"brown"},{id:2, name:"choco", desc:"black"},{id:3, name:"dduk", desc:"white"}
]

function App() {
  return (
    <div>
      {FoodLike.map( dish => (
        <Food key={dish.id} name={dish.name} desc={dish.desc}/>
      ))}
    </div>
  );
}

export default App;

 

- react 자체적으로 필요한 key값은 id로 넣어주기

 

 

우리가 원하는 props가 우리가 갖고있는 props인지 체크하는 방법

node.js에 설치 - npm i prop-types

= 내가 전달받은 props가 내가 원하는 props인지를 확인해줌

(number인지? string인지? isRequired 꼭 필요한건지?)

 

-> package.json에서 제대로 설치되어있는지 확인

 

 

import React from 'react';
import PropTypes from "prop-types";

function Food({name, desc, rating}) {
  return (
    <div>
      <h1>i love {name}</h1>
      <h2>{rating} / 5</h2>
      <p>this color is {desc}</p>
    </div>
  );
}

Food.propTypes = {
  name: PropTypes.string.isRequired,
  desc: PropTypes.string.isRequired,
  rating: PropTypes.number.isRequired
}

const FoodLike = [
  {id:1, name:"coffee", desc:"brown", rating: 5},
  {id:2, name:"choco", desc:"black", rating: 4.8},
  {id:3, name:"dduk", desc:"white", rating: 4.5}
]

function App() {
  return (
    <div>
      {FoodLike.map( dish => (
        <Food key={dish.id} name={dish.name} desc={dish.desc} rating={dish.rating}/>
      ))}
    </div>
  );
}

export default App;

 

- rating props가 string인지 확인 -> number이기 때문에 에러가 생김

-> number로 바꿔주면 에러가 생기지 않는다.

 

array, boolean, true, false, object인지 / 있는지, 없는지 - propTypes 체크할 수 있음

 

 

 

PropTypes와 함께 하는 타입 확인 – React

A JavaScript library for building user interfaces

ko.reactjs.org

 

state

class사용

 

import React from 'react';
import PropTypes from "prop-types";

class App extends React.Component {
  state = {
    count : 0
  }

  add = () => {
    //this.setState({count : this.state.count +1});
    this.setState(current => ({count : current.count +1}));
  }
  minus = () => {
    //this.setState({count : this.state.count -1});
    this.setState(current => ({count : current.count -1}));
  }

  render(){
    return(
      <div>
        <h1>This number is : {this.state.count}</h1>
        <button onClick={this.add}>add</button>
        <button onClick={this.minus}>minus</button>
      </div>
    )
  }
}

export default App;

 

- 매순간 setState를 호출할 때마다 react는 새로운 state와 함께 render function을 호출한다

 

 

life cycle method

life cycle method를 가지는데, life cycle method은 기본적으로 react가 component를 생성하는, 없애는 방법이다

 

 //Mounting
 //1 constructor가 가장 먼저 실행
 //2 render함수 실행
 
 //3 component가 render할 때,
 componentDidMount() {
    console.log("Component rendered");
  }
  
  //Updating
  componentDidUpdate() {
    console.log("I just updated");
  }
  
  //페이지를 바꿀 때, component가 죽을 때,
  componentWillUnmount() {
    console.log("Goodbye, cruel world");
  }

 

 

React.Component – React

A JavaScript library for building user interfaces

ko.reactjs.org

 

 

Lifecycle Methods to Class

mounting - 처음으로 DOM에 rendering될 때 componentDidMount( ) unmounting - 생성된 DOM이 제거 될 때 componentWillUnmount( )  the component Lifecycle (자주 사용되는 Lifecycle위주로 작성됨) Mounting -..

heeyeonjeong.tistory.com

 

 

data fetch하기

componentDidMount에서 data를 fetch하는 것이다

(쉽게 말해, 로딩이 되면 화면을 구성하는 것처럼,,)

 

import React from 'react';

class App extends React.Component {
  state = {
    isLoading: true
  }

  componentDidMount(){
    setTimeout(() => {
      this.setState({isLoading:false})
    }, 3000);
  }

  render(){
   //return <div>{this.state.isLoading ? "Loading..." : "im ready"}</div> 
    const {isLoading} = this.state
    return <div>{isLoading ? "Loading..." : "im ready"}</div>
  }
}

export default App;

 

- 처음에 render를 하면 호출되는 life cycle method인 componentDidMount( ) 사용

- setTimeout으로 6초 뒤에 'isLoading' state를 'im ready'로 바꿔줌

'React' 카테고리의 다른 글

Lifecycle Methods to Class  (0) 2020.11.05
react 추가 study  (0) 2020.11.04
Update, Delete 기능 구현  (0) 2020.10.28
Component 이벤트 만들기  (0) 2020.10.26
props / state  (0) 2020.10.22