React.js에서 선언적과 명령 적의 차이점은 무엇입니까?
최근에 저는 Facebook JavaScript 라이브러리 React.js를 사용하는 기능과 방법에 대해 많은 연구를했습니다. 종종 자바 스크립트 세계에서 두 개의 프로그래밍 스타일의 나머지의 차이 말할 때 declarative
와 imperative
했나요된다.
둘의 차이점은 무엇입니까?
react가 가지고있는 것과 같은 선언적 스타일을 사용하면 "It should look like this"라고 말하여 애플리케이션의 흐름과 상태를 제어 할 수 있습니다. 명령형 스타일은이를 바꾸고 "이것이 당신이해야 할 일"이라고 말함으로써 당신의 애플리케이션을 제어 할 수있게합니다.
선언적의 이점은 상태를 나타내는 구현 세부 사항에 얽매이지 않는다는 것입니다. 애플리케이션보기를 일관되게 유지하는 조직 구성 요소를 위임하므로 상태에 대해서만 걱정하면됩니다.
프레임 워크에 대한 일종의 은유 인 집사가 있다고 상상해보십시오. 그리고 당신은 저녁을 만들고 싶습니다. 명령형 세계에서는 저녁 식사를 만드는 방법을 단계별로 알려줄 것입니다. 다음 지침을 제공해야합니다.
Go to the kitchen
Open fridge
Remove chicken from fridge
...
Bring food to the table
선언적 세계에서는 원하는 것을 간단히 설명 할 수 있습니다.
I want dinner with chicken.
집사가 닭고기를 만드는 방법을 모르면 선언적 스타일로 작업 할 수 없습니다. Backbone이 특정 작업을 수행하기 위해 자신을 변경하는 방법을 모르는 것처럼 해당 작업을 수행하도록 지시 할 수 없습니다. 예를 들어 React는 "닭을 만드는 방법을 알고"있기 때문에 선언적 일 수 있습니다. 주방과 인터페이스하는 방법 만 아는 백본과 비교.
상태를 설명 할 수 있으면 버그의 표면적이 크게 줄어들어 이점이 있습니다. 반면에 상태를 구현하는 방법을 위임하거나 추상화하기 때문에 상황이 발생 하는 방식 에 대한 유연성이 떨어질 수 있습니다.
"좋아요"버튼과 같은 간단한 UI 구성 요소를 상상해보십시오. 탭하면 이전에 회색 이었으면 파란색으로, 이전에 파란색 이었으면 회색으로 바뀝니다.
이를 수행하는 필수 방법은 다음과 같습니다.
if( user.likes() ) {
if( hasBlue() ) {
removeBlue();
addGrey();
} else {
removeGrey();
addBlue();
}
}
기본적으로 현재 화면에있는 내용을 확인하고 이전 상태의 변경 사항을 취소하는 것을 포함하여 현재 상태로 다시 그리는 데 필요한 모든 변경 사항을 처리해야합니다. 실제 시나리오에서 이것이 얼마나 복잡한 지 상상할 수 있습니다.
반대로 선언적 접근 방식은 다음과 같습니다.
if( this.state.liked ) {
return <blueLike />;
} else {
return <greyLike />;
}
선언적 접근 방식은 관심사를 분리하기 때문에이 부분에서는 UI가 개별 상태로 표시되는 방식 만 처리하면되므로 이해하기 훨씬 간단합니다.
이것은 큰 비유입니다.
* 긴급 대응 : 주차장 북쪽 출구로 나와 좌회전 Bangerter Highway 출구가 나올 때까지 I-15 남쪽으로 타십시오. Ikea에가는 것처럼 출구에서 우회전하십시오. 직진하여 첫 번째 신호등에서 우회전하십시오. 다음 신호등을 통과 한 후 다음 좌회전하십시오. 우리 집은 # 298입니다.
선언적 답변 : 제 주소는 298 West Immutable Alley, Draper Utah 84020 *입니다.
https://tylermcginnis.com/imperative-vs-declarative-programming/
React (선언적)와 JQuery (명령어)를 비교하여 차이점을 보여주는 것이 가장 좋습니다.
React에서는 render()
이전 UI 상태에서 새 UI 상태로 전환하는 방법에 대해 걱정하지 않고 메서드 에서 UI의 최종 상태 만 설명하면됩니다 . 예 :
render() {
const { price, volume } = this.state;
const totalPrice = price * volume;
return (
<div>
<Label value={price} className={price > 100 ? 'expensive' : 'cheap'} ... />
<Label value={volume} className={volume > 1000 ? 'high' : 'low'} ... />
<Label value={totalPrice} ... />
...
</div>
)
}
반면에 JQuery를 사용하려면 UI 상태를 명령 적으로 전환해야합니다 (예 : 레이블 요소 선택 및 해당 텍스트 및 CSS 업데이트).
onPriceUpdated(price) {
$("#price-label").val(price);
$("#price-label").toggleClass('expansive', price > 100);
$("#price-label").toggleClass('cheap', price < 100);
updateTotalPrice();
}
onVolumeUpdated(volume) {
$("#volume-label").val(volume);
$("#volume-label").toggleClass('high', volume > 1000);
$("#volume-label").toggleClass('low', volume < 1000);
updateTotalPrice();
}
updateTotalPrice() {
const totalPrice = price * volume;
$("#total-price-label").val(totalPrice);
...
}
실제 시나리오에서는 훨씬 더 많은 UI 요소와 그 속성 (예 : CSS 스타일 및 이벤트 리스너) 등이 업데이트 될 것입니다. JQuery를 사용하여 필수적으로이 작업을 수행하면 복잡하고 지루해집니다. UI의 일부를 업데이트하는 것을 잊거나 오래된 짝수 리스너 (메모리 누수) 등을 제거하는 것을 잊기 쉽습니다. 여기에서 버그가 발생합니다. 즉, UI 상태와 모델 상태가 동기화되지 않습니다.
모델 상태를 업데이트하기 만하면되고 React는 UI와 모델 상태를 동기화 상태로 유지할 책임이 있기 때문에 React의 선언적 접근 방식에서는 동기화되지 않은 상태가 발생하지 않습니다.
- 후크 아래에서 React는 명령형 코드를 사용하여 변경된 모든 DOM 요소를 업데이트합니다.
You may also read my answer for What is the difference between declarative and imperative programming?.
PS: from above jQuery example, you may think what if we put all the DOM manipulations in a updateAll()
method, and call it every time when any of our model state changes, and the UI will never be out of sync. You are correct, and this is effectively what React does, the only difference is that jQuery updateAll()
will cause many unnecessary DOM manipulations, but React will only update changed DOM elements using its Virtual DOM Diffing Algorithm.
A real-life parallel in the imperative world would be entering a bar for a beer, and giving the following instructions to the bartender: --Take a glass from the shelf --Put the glass in front of the draft --Pull down the handle until the glass is full --Pass me the glass.
In the declarative world, instead, you would just say: "Beer, please."
The declarative approach of asking for a beer assumes that the bartender knows how to serve one, and that is an important aspect of the way declarative programming works.
In declarative programming, developers only describe what they want to achieve and there's no need to list all the steps to make it work.
The fact that React offers a declarative approach makes it easy to use, and consequently, the resulting code is simple, which often leads to fewer bugs and more maintainability.
Since React follows a declarative paradigm, and there's no need to tell it how to interact with the DOM; you just DECLARE what you want to see on the screen and React does the job for you.
- Declarative is allowed you to control all view. (like as state management)
- the Imperative is allowed you control around view. (like as $(this))
I'll start with an analogy: I have two cars, in my two cars I want the temperatue inside my car to be normal room temperature ~ 72°F. In the first (older) car, there's two knobs to control the temperature (1 knob to control the temperature and 1 knob to control the airflow). When it gets too hot, I have to adjust the first knob to lower the temperature and maybe change the airflow) and vice verse if it's too cold. This is imperative work! I have to manage the knobs myself. In my second (newer) car, I can set/declare the temperature. Which means I don't have to fiddle with the knobs to adjust the temperature my car knows I declare/set it to 72°F and my car will do the imperative work to get to that state.
React is the same, you declare the markup/template and stat then React does the imperative work to keep the DOM in sync with your app.
<button onClick={activateTeleporter}>Activate Teleporter</button>
Instead of using .addEventListener()
to set up event handling, we declare what we want. When the button is clicked, it'll run the activateTeleporter
function.
Imperative code instructs JavaScript on how it should perform each step. With declarative code, we tell JavaScript what we want to be done, and let JavaScript take care of performing the steps.
React is declarative because we write the code that we want and React is in charge of taking our declared code and performing all of the JavaScript/DOM steps to get us to our desired result.
Declarative programming is a programming paradigm … that expresses the logic of a computation without describing its control flow.
Imperative programming is a programming paradigm that uses statements that change a program’s state.
ref link:-https://codeburst.io/declarative-vs-imperative-programming-a8a7c93d9ad2
'Programing' 카테고리의 다른 글
스크롤 할 때 메뉴 막대를 상단에 고정 (0) | 2020.11.03 |
---|---|
onResume ()을 사용하는 방법? (0) | 2020.11.03 |
JavaScript에서 비트 연산자를 어디에서 사용합니까? (0) | 2020.11.03 |
람다로 목록에서 중복 값을 제거하는 가장 빠른 방법 <> (0) | 2020.11.03 |
javascript : 텍스트 선택 비활성화 (0) | 2020.11.03 |