React -5일차

홍주환·2022년 6월 30일
0

동기
● 작업(task)들이 순차적으로 이루어 지는 것

현재 작업하고 있으면 다른 작업들을 Blocking
비동기
작업 (task)들이 순차적으로 이루어지지 않는다.
다른 작업들은 non-blocking
Ajax 통신

stateful, stateless
1. 컴포넌트를 나누는 또 다른 방식이다.
2. stateful 컴포넌트 : 모든 state를 들고 있는 컴포넌트
3.stateless 컴포넌트 :state 를 안들고 있고 Props와 같이 받은 데이터만
보여주는 컴포넌트
4. 리엑트는 단방향 통신이라서 부모에서 자식쪽으로는 데이터 전달이 가능하지만 자식에서 부모방향으로는 줄 수 없다. 자식과 자식 간에 도 연관성이 없다면 줄 수 없다.

5.자식 쪽에서 이벤트를 발생시키는 시점에서 부모가 모든 데이터를 가지고 있다가 자식쪽으로 데이터 전달

실습 날씨 앱 만들기
1. 먼저 날씨API를 받아오기 위해 KEY를 설치한다.
2.https://openweathermap.org/
3. 회원가입후 key를 확인한다.

필요한 확장팩 설치하기
1)ES7 react 설치하기
rcc+enter 처럼 간단 명령어로 기본 골격 구조 만들어 줌
명령어 : rafce+ enter
2)부트스트랩 패키지 설치
3)npm install react-bootstrap
bootstrap 설치
스피너 패키지 설치
react spinner 검색
https://www.npmjs.com/package/react-sppiners

설치 명령어 : npm-install--save react-spinners

4)코드 입력
1)APP.js

import React, { useState,useEffect } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css':
import './App.css';
import {Contatiner } from'react-bootstrap';
import WeatherButton from './components/WeatherButton';
import WeatherBox from './components/WeatherBox';
oader } from'react-spinners';

{'paris, 'new york', 'tokyo','seoul'};
//https: //openweathermap.org의키
const API_KEY = '68426cc698229c9257d29f7fc86b3a6f';

const App =()=> {
const [loading,setLoading]=useState(false);
const [city,setCity]- useState(null);  //도시 정보초기 값 설정
const [weather, setweather]=useState(null);// 날씨 정보'
const[apiError,setAPIError]=useState('');

//데이터 불러오기
useEffect (()=> {
if(city ==null) {
setLoading(true);
getCurrentLocation();// 도시 정보가 없다면 현재 정보를 불러옴
}else {
setCity(city);
 }
};
return (
<Contatiner className="vh-100">
{loading ? (
<div className="w-100 vh-100 d-flex justify-content-center align-items-center">
<ClipLoader color="#f86c6b" size={150}lodading={loading}/>
</div>
: !apiError ?(
<div class="main-container">
<WeatherBox weather={weather}/> {*정보 내려주기*/}
<WeatherButton
 cities={cities}
 handleCityChange={handleCityChange}
 selectedCity={city}
 /> {/*정보 내려주기*/}
 </div>
 ) : (
 apiError
 )}
 </Contatiner>
 );
 };
 export default App;
 

현재 위치 불러오기
get current location javascript 검색
https://www.w3schools.com/html/
html5_geolocation.asp 사이트 참고
2)weatherBox.js

import React from 'react';
import {Card} from'react-bootstrap';

const WeatherBox= ({weather})=>{
//섭씨,화씨 계산
const temperatureC=
weather weather.main?(weather.main.temp -273.15).toFixed(2):'';
const temperatureF=
weather weather.main
? (((weather.main.temp-273.15) *9) /5+32).toFixed(2)
:'';

return (
<Card className="weather-card">
{/*<Card.Img src="holder.js/100px270" alt="Card image" /> */}
<Card. Title> {weather?.name}</Card/Title>
<Card. Text className="text-success h1">
{'${temperatureC} "c/ ${temperatureF} F} {/*섭씨,화씨 나타내기*/}
</Card.Text>
</Card. Text>
</Card.ImgOverlay>
</Card>
);
};
export default weatherBox;

3)weatherButton.js

import Reactfrom 'react';
import {Button } from 'react-bootstrap';

const WeatherButton = ({ cities,selectedCity,handleCityChange})=>{
return (
<div class="menu-container">
<Button
 variant={'${selectedCity ===null? outline-waring': 'waring'}'}
 onClick={()=> handleCityChange('current')}
 >
  Current Location
  </Button>
  {/*배열에서 가져올 때는 map */}
  {cities.map ((city)=> (
  <Button 
    variant={'${selectedCity===city? 'outline-warning' : 'warning'}'}
    onClick={()=>handleCityChange(city)}
    
    >
     {city}
     </Button>
     ))}
     </div>
       );
     };
 export default weatherButton;

weatherButton에서 weatherBox에 정보를 전달해야하는데
단방향 통신이라 자식간 정보전달을 할 수 없다.

그래서 모든 데이터를 소유하고 있는 부모 App.js에서 데이터를 자식weatherBox로 넘겨준다.
4)App.css

  background:url(https://cdn.pixbay.com/photo/2017.01/17/16/45/night-1987408_960
  height : 100vh;
  background-repeat : no-repeat;
  background-size: cover;
  }
  weather-card{
  backgroundcolor-color: rgba(52.52.52.7) !important;
  padding: 50px;
  border: 2px solid #fff;
  border-radius :20px;
  max-width :700px;
  width:100%;
  height: 300px;
  }
  .main container{
  display: flex;
  flex-direction : columnl;
  align-items : center;
  justify-content : center;
  height :100%;
  }
  menu container{
  display : flex;
  justify-content:center;
  background-color : #000;
  border-radius: 60px;
  max-width :700px;
  width :100%;
  padding : 30px;
  margin-top:30px;
  }
  .ment-container Button{
  margin-right:30px;
  }
  .menu-container Button:hover{
  background-color#ffc107;
  ```
  
  2) 학습한 내용 중 어려웠던 점
  
  코드를 작성하고 이미지를 첨부하고  결과물을 보는과정이 어려웠다.
  
  3)나름대로 연습해야겠다.
  
  4)학습소감
  
  REACT 에 대해 배웠는데 코드를 작성하여 도시마다 날씨정보를  알수 있다는게 흥미로웠다.
  
  아직 익숙지 않아 복습을 많이 해야겠다.
  
  
  
  
  

  

 

profile
열심히 배우자

0개의 댓글