정말 많이 쓰이는 API입니다. 컴포넌트가 DOM 위에 생성되는 상태에 따라 실행되는 메소드들입니다.

 

구성 요소에는 수명주기가 있습니다. 구성 요소는 인스턴스화, 마운트, 렌더링 및 업데이트, 마운트 해제 및 소멸됩니다. 라이프 사이클은 단순하고 일관된 추상화 계층을 제공하여 브라우저 API의 복잡성을 관리하는 데 도움이됩니다. 라이프 사이클을 사용하면 렌더링을보다 세밀하게 제어하기 위해 각 단계에서 사용자 지정 코드를 선택적으로 실행할 수도 있습니다.

구성 요소 수명주기의 각 단계를 살펴 보겠습니다.

 

Mounting Cycle

 

constructor(object props)

 

컴포넌트 클래스가 인스턴스화됩니다. 생성자에 대한 매개 변수 는 부모 요소에 의해 지정된대로 요소의 initial 입니다. 

선택적으로 객체를에 할당하여 요소의 초기 상태를 지정할 수 있습니다 . 

현재이 요소에 대해 기본 UI가 렌더링되지 않았습니다. propsthis.state

 

componentWillMount()

이 메소드는 렌더링이 처음으로 발생하기 전에 한 번만 호출됩니다. 현재이 요소에 대해 렌더링 된 기본 UI는 없습니다.

 

render() -> React Element

render 메소드는 렌더링하기 위해 React Element를 반환해야합니다 (또는 아무것도 렌더링하지 않으려면 null).

 

componentDidMount()

이 메소드는 렌더링이 처음 발생한 후 한 번만 호출됩니다. 이제이 요소의 기본 UI가 렌더링을 마치고 직접 조작하기 위해 액세스 할 수 있습니다 . 를 사용하여 비동기 API 호출을하거나 지연된 코드를 실행 해야하는 경우 일반적으로이 방법으로 수행해야합니다.this.refssetTimeout

Updating Cycle

componentWillReceiveProps(object nextProps)

이 구성 요소의 부모가 새로운 세트를 전달했습니다 . 이 구성 요소는 다시 렌더링됩니다. 

메소드가 호출 되기 전에 선택적 으로이 컴포넌트의 내부 상태를 업데이트하기 위해 호출  수 있습니다 .propsthis.setState()render

 

shouldComponentUpdate(object nextProps, object nextState) -> boolean

 의 다음 값을 기반으로 구성 요소는 다시 렌더링하거나 다시 렌더링하지 않을 수 있습니다. 이 메소드의 기본 클래스 구현은 항상 리턴합니다 (구성 요소  다시 렌더링 해야 함 ). 최적화의 경우,이 메소드를 오버라이드 (override) 중 여부를 확인 또는 수정 된, 예를 들어, 이러한 객체에있는 각각의 키 / 값의 평등 테스트를 실행합니다. 리턴 하면 메소드가 호출되지 않습니다.props state true props state false render

 

componentWillUpdate(object nextProps, object nextState)

이 메소드는 다시 렌더링하기로 결정한 후에 호출됩니다. 업데이트가 이미 진행 중이므로 여기에 전화하지 않을 수 있습니다 .this.setState()

 

render() -> React Element

이 메소드는 return을 가정하여 호출 됩니다. render 메소드는 렌더링하기 위해 React Element를 반환해야합니다 (또는 아무것도 렌더링하지 않으려면 null).shouldComponentUpdatetrue

 

componentDidUpdate(object prevProps, object prevState)

이 메소드는 다시 렌더링이 발생한 후에 호출됩니다. 이 시점에서이 컴포넌트의 기본 UI가 메소드 에서 리턴 된 React 요소를 반영하도록 업데이트되었습니다 .render()

 

이글은 http://www.react.express/lifecycle_api 에서 참조한 글입니다. React를 시작하기에 앞서 기본중 기본으로 잘 외워둡시당

'React' 카테고리의 다른 글

React Library 모음  (0) 2019.09.05
React는 알고 코딩해야지 !  (0) 2019.09.04
React의 react-moment library 를 사용해보자  (0) 2019.08.21
템플릿 리터럴 이란 ?!  (0) 2019.08.20
React Styled Component  (0) 2019.08.19

https://www.npmjs.com/package/react-moment

 

moment

Parse, validate, manipulate, and display dates

www.npmjs.com

react-moment 는 날짜 관련 작업을 위한 js 라이브러리입니다 !

예제로는 

 

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            const dateToFormat = '1976-04-19T12:59-0500';
            <Moment>{dateToFormat}</Moment>
        );
    }
}

 

이런식으로 Moment를 사용해주면 Outputs 값으로

<time>Mon Apr 19 1976 12:59:00 GMT-0500</time>

이렇게 나옵니다.

 

자식이 아닌 속성을 사용하여 날짜를 전달하려는 경우 위의 예제를 이런 식으로 작성할 수도 있습니다.

 

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            const dateToFormat = '1976-04-19T12:59-0500';
            <Moment date={dateToFormat} />
        );
    }
}

 

날짜 값은 문자열, 객체, 배열 또는 Date인스턴스 일 수 있습니다.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            const dateToFormat = new Date('1976-04-19T12:59-0500');
            <Moment date={dateToFormat} />
        );
    }
}

 

 

moment는 기본적으로 시간은 60 초 (60000 밀리 초)마다 업데이트됩니다. interval소품을 사용하여 업데이트를 변경하거나 비활성화하십시오. 30 초 (30000 밀리 초)마다 시간을 업데이트합니다.

 

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment interval={30000}>
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

Disables updating.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment interval={0}>
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

Formatting

주어진 형식 문자열에 따라 날짜를 형식화합니다.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment format="YYYY/MM/DD">
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

Outputs

<time>1976/04/19</time>

 

Parsing Dates

parse = {string}

 

Moment는 대부분의 표준 날짜 형식을 구문 분석 할 수 있습니다. parse비표준 일 때 주어진 날짜를 구문 분석하는 방법을 순간적으로 알려주 려면 속성을 사용하십시오 .

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment parse="YYYY-MM-DD HH:mm">
                1976-04-19 12:59
            </Moment>
        );
    }
}

 

Add and Subtract

add={object}

subtract={object}

주어진 날짜에서 기간을 더하고 빼는 데 사용되며 기간은 객체 리터럴로 표시됩니다.\

 

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        const date = new Date();
 
        return (
            <div>
                <Moment add={{ hours: 12 }}>{date}</Moment>
                <Moment add={{ days: 1, hours: 12 }}>{date}</Moment>
                <Moment subtract={{ hours: 12 }}>{date}</Moment>
                <Moment subtract={{ days: 1, hours: 12 }}>{date}</Moment>
            </div>
        );
    }
}

 

From Now

때로는 timeago 또는 상대 시간이라고도하며 날짜 를 지금부터 시간으로 표시합니다 ( 예 : "5 분 전").

 

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment fromNow>1976-04-19T12:59-0500</Moment>
        );
    }
}

위와 아래 같은 코드 생략 가능

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment fromNow ago>1976-04-19T12:59-0500</Moment>
        );
    }
}

Outputs

<time>40 years ago</time>

 

From Now During

from = {string}

fromNowDuring  설정하면 fromNow  마찬가지로 상대 시간이 표시 되지만 해당 형식 이 사용 된 후에는 밀리 초 단위의 값만 표시 됩니다.

 

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment from="2015-04-19">1976-04-19T12:59-0500</Moment>
        );
    }
}

Outputs

<time>39 years</time>

 

To Now

 fromNow와 비슷하지만 반대 간격을 제공합니다.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment toNow>1976-04-19T12:59-0500</Moment>
        );
    }
}

Outputs:

<time>40 years ago</time>

To

to={String}

 

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment to="2015-04-19">1976-04-19T12:59-0500</Moment>
        );
    }
}

  Outputs:

<time>39 years</time>

 

Filter

filter={function}

렌더링 전에 날짜 값을 수정 / 변환하는 기능입니다.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        const toUpperCaseFilter = (d) => {
            return d.toUpperCase();
        };
 
        return (
            const dateToFormat = '1976-04-19T12:59-0500';
            <Moment filter={toUpperCaseFilter}>{dateToFormat}</Moment>
        );
    }
}

 

Outputs:

<time>MON APR 19 1976 12:59:00 GMT-0500</time>

 

With Title

withTitle={bool}

title완전한 날짜를 가진 요소에 속성을 추가합니다 .

 

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment format="D MMM YYYY" withTitle>
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

Outputs:

<time title="1976-04-19T12:59-0500">19 Apr 1976</time>

 

Title Format

titleFormat={string}

속성을 title사용할 때 날짜의 형식을 지정 하는 방법 withTitle

 

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment titleFormat="D MMM YYYY" withTitle>
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

Outputs:

<time title="19 Apr 1976">1976-04-19T12:59-0500</time>

Difference

diff={string}

decimal={bool}

unit={string}

 

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <div>
              <Moment diff="2015-04-19">1976-04-19T12:59-0500</Moment>
              <Moment diff="2015-04-19" unit="days">1976-04-19T12:59-0500</Moment>
              <Moment diff="2015-04-19" unit="years" decimal>1976-04-19T12:59-0500</Moment>
            </div>
        );
    }
}

 

Duration

duration={string}

date={string}

두 날짜 사이의 기간 (경과 시간)을 표시합니다. duration은 date 시간적으로 뒤에 있어야 합니다.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment duration="2018-11-1T10:59-0500"
                    date="2018-11-1T12:59-0500"
            />
        );
    }
}

 

Duration From Now

durationFromNow={bool}

현재 날짜와 제공된 날짜 시간 사이의 지속 시간 (경과 시간)을 표시합니다.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment date="2018-11-1T12:59-0500"
                    durationFromNow
            />
        );
    }
}

 

Unix Timestamps

unix={bool}

주어진 날짜 값을 유닉스 타임 스탬프로 구문 분석하도록 Moment에 지시합니다.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        const unixTimestamp = 198784740;
        return (
            <Moment unix>{unixTimestamp}</Moment>
        );
    }
}

Outputs:

<time>Mon Apr 19 1976 12:59:00 GMT-0500</time>

 

Local

local={bool}

현지 시간으로 결과를 출력합니다

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment local>
                2018-11-01T12:59-0500
            </Moment>
        );
    }
}

Outputs:

<time>Thu Nov 01 2018 18:59:00 GMT+0100</time> //현재시간

 

Timezone

tz={string}

시간대를 설정합니다. 서버 측 렌더링 (SSR)을 사용하려면 클라이언트와 서버가 공통 시간대를 기반으로 동일한 날짜 시간을 제공해야합니다.  tz속성은 공통 시간대 설정을 활성화합니다.

import React  from 'react';
import Moment from 'react-moment';
import 'moment-timezone';
 
export default class MyComponent extends React.Component {
    render() {
        const unixTimestamp = 198784740;
        return (
            <Moment unix tz="America/Los_Angeles">
                {unixTimestamp}
            </Moment>
        );
    }
}

Outputs:

<time>Mon Apr 19 1976 09:59:00 GMT-0800</time>

 

Calender

calendar={object|bool}

달력 기능에 사용되는 문자열을 사용자 정의하십시오.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        const calendarStrings = {
            lastDay : '[Yesterday at] LT',
            sameDay : '[Today at] LT',
            nextDay : '[Tomorrow at] LT',
            lastWeek : '[last] dddd [at] LT',
            nextWeek : 'dddd [at] LT',
            sameElse : 'L'
        };
 
        return (
            <Moment calendar={calendarStrings}>
                '1976-04-19T12:59-0500'
            </Moment>
        );
    }
}

Locale

locale = {string}

날짜를 표시하는 데 사용되는 Locale을 설정합니다.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        const dateToFormat = '1976-04-19T12:59-0500';
        return (
            <Moment locale="de">{dateToFormat}</Moment>
        );
    }
}

 

참고 경우에 따라 언어 파일이 순간적으로 자동으로로드되지 않고 수동으로로드해야합니다. 예를 들어 프랑스어 로캘을 사용하려면 부트 스트랩 (예 : index.js) 스크립트에 다음을 추가하십시오.

import 'moment/locale/fr';

 

Element

element={string|React.Component}

렌더링 할 요소 유형 (문자열 또는 함수)

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment element="span">1976-04-19T12:59-0500</Moment>
        );
    }
}

Outputs:

<span>Mon Apr 19 1976 12:59:00 GMT-0500</span>

OnChange

onChange={func}

onChange소품은 기본적으로 60 초마다 한 날짜가 업데이트 될 때마다 호출됩니다. 함수는 새로운 날짜 값을받습니다.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment onChange={(val) => { console.log(val); }}>
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

 

Other Props

다른 속성은 <time>요소에 전달됩니다 .

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment className="datetime" aria-hidden={true}>
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

 

Pooled Timer

기본적으로 마운트 된 각 <Moment />인스턴스 에 대해 타이머가 작성되어 날짜 값을 업데이트합니다. 이는 페이지에 인스턴스가 몇 개인 경우에 좋습니다. 그러나 마운트 된 인스턴스가 많은 경우 성능이 저하 될 수 있습니다. 풀링 된 타이머를 사용하여 문제를 해결합니다.

풀링 된 타이밍이 활성화되면 react-moment는 단일 타이머 만 사용하여 마운트 된 모든 <Moment />인스턴스 를 업데이트 합니다. 풀링 된 타이밍은 호출 startPooledTimer()하여 활성화되고을 호출 하여 중지됩니다 clearPooledTimer().

startPooledTimer()부트 스트랩 스크립트 (보통 index.js)에서 정적 메소드를 호출하여 타이머를 초기화하십시오

 

import React from 'react';
import ReactDOM from 'react-dom';
import Moment from 'react-moment';
import App from './components/app';
 
// Start the pooled timer which runs every 60 seconds
// (60000 milliseconds) by default.
Moment.startPooledTimer();
 
// Or set the update interval. This will update the mounted
// instances every 30 seconds.
// Moment.startPooledTimer(30000);
 
ReactDOM.render(<App />, document.getElementById('mount'));

 

이상으로 npm moment의 속성 값과 내용을 알아보았습니다.

npmjs.com에서 번역해온 글로 수정을 조금 했습니다. 감사합니다:)

'React' 카테고리의 다른 글

React는 알고 코딩해야지 !  (0) 2019.09.04
React Component LifeCycle API 이란?  (0) 2019.08.23
템플릿 리터럴 이란 ?!  (0) 2019.08.20
React Styled Component  (0) 2019.08.19
리액트의 인라인 스타일링 ! React Inline Styling  (0) 2019.08.19

ES6는 템플릿 리터럴(Template literal)이라고 불리는 새로운 문자열 표기법을 도입하였다. 템플릿 리터럴은 일반 문자열과 비슷해 보이지만, ‘ 또는 “ 같은 통상적인 따옴표 문자 대신 백틱(backtick) 문자 `를 사용한다.

 

const test = `템플릿 리터럴`;

일반적인 문자열에서 줄바꿈은 허용되지 않으며 공백(white-space)를 표현하기 위해서는 백슬래시(\)로 시작하는 이스케이프 시퀀스(Escape Sequence)를 사용하여야 한다. ES6 템플릿 리터럴은 일반적인 문자열과 달리 여러 줄에 걸쳐 문자열을 작성할 수 있으며 템플릿 리터럴 내의 모든 white-space는 있는 그대로 적용된다.

 

const test = `<div> hihi </div>`;

 

템플릿 리터럴은 + 연산자를 사용하지 않아도 간단한 방법으로 새로운 문자열을 삽입할 수 있는 기능을 제공한다. 이를 문자열 인터폴레이션(String Interpolation)이라 한다.

const firstName = 'Hong';
const LastName = 'gildong';

//ES 5
console.log('My nmae is ' + first + ' ' + second);

//ES 6
console.log(`My name is ${firstName} ${LastName}`);

문자열 인터폴레이션은 ${ … }으로 표현식을 감싼다. 문자열 인터폴레이션 내의 표현식은 문자열로 강제 타입 변환된다.

 

console.log(`1 + ` = ${1 + 1}`) 

// 1 + 1 = 2

 

참고 url : https://poiemaweb.com/es6-template-literals

Postman의 GET 방식으로 테스트를 해보겠습니다.

 

첫 번째로 https://openweathermap.org/

 

Сurrent weather and forecast - OpenWeatherMap

Agricultural API for Satellite and Weather data This is a set of APIs that can provide Satellite imagery, Weather data and other products for agriculture, based on geodata. You can easily power your application with a combination of satellite and weather d

openweathermap.org

사이트에 들어가서 회원가입을 합니다.

 

그러면 등록한 이메일로

이렇게 API KEY가 옵니다.

Postman을 킨 뒤 

my api key에 받은 key값을 넣어줍니다 그러면 json 형식으로 

값이 날라옵니다 q 값에 자기가 원하는 지역을 넣어줍니다 ex) Seoul, London

그러면

이렇게 날씨 값들이 json 형식으로 날아옵니다 !

감사합니다

'API & library' 카테고리의 다른 글

node-cron 이란 ?  (0) 2019.09.02

+ Recent posts