Difference between declarative and imperative in React.js?

后端 未结 9 509
日久生厌
日久生厌 2020-11-30 17:29

Recently I\'ve been studying a lot about the functionality and the ways to use the Facebook JavaScript library React.js. When speaking of its differences to the rest of the

相关标签:
9条回答
  • 2020-11-30 17:47

    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.

    0 讨论(0)
  • 2020-11-30 17:53

    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

    0 讨论(0)
  • 2020-11-30 17:58

    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.

    0 讨论(0)
提交回复
热议问题