Difference between declarative and imperative in React.js?

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 JavaScript world often the two programming styles declarative and imperative are mentionned.

What's the difference between both?


A declarative style, like what react has, allows you to control flow and state in your application by saying "It should look like this". An imperative style turns that around and allows you to control your application by saying "This is what you should do".

The benefit of declarative is that you don't get bogged down in the implementation details of representing the state. You're delegating the organizational component of keeping your application views consistent so you just have to worry about state.

Imagine you have a butler, who is kind of a metaphor for a framework. And you would like to make dinner. In an imperative world, you would tell them step by step how to make dinner. You have to provide these instructions:

Go to kitchen
Open fridge
Remove chicken from fridge
...
Bring food to table

In a declarative world, you would simply describe what you want

I want a dinner with chicken.

If your butler doesn't know how to make chicken, then you cannot operate in a declarative style. Just like if backbone doesn't know how to mutate itself to do a certain task, you can't just tell it to do that task. React is able to be declarative because it "knows how to make chicken", for example. Compared to backbone, which only knows how to interface with the kitchen.

Being able to describe the state reduces the surface area for bugs dramatically, which is a benefit. On the other hand, you might have less flexibility in how things occur because you're delegating or abstracting away how you implement the state.


Imagine a simple UI component, such as a "Like" button. When you tap it, it turns blue if it was previously grey, and grey if it was previously blue.

The imperative way of doing this would be:

if( user.likes() ) {
    if( hasBlue() ) {
        removeBlue();
        addGrey();
    } else {
        removeGrey();
        addBlue();
    }
}

Basically, you have to check what is currently on the screen and handle all the changes necessary to redraw it with the current state, including undoing the changes from the previous state. You can imagine how complex this could be in a real-world scenario.

In contrast, the declarative approach would be:

if( this.state.liked ) {
    return <blueLike />;
} else {
    return <greyLike />;
}

Because the declarative approach separates concerns, this part of it only needs to handle how the UI should look in a sepecific state, and is therefore much simpler to understand.


Imperative Code:

When JavaScript code is written imperatively, we tell JavaScript exactly what to do and how to do it. Think of it as if we're giving JavaScript commands on exactly what steps it should take.

For example, I give you the humble for loop:

const people = ['Amanda', 'Geoff', 'Michael', 'Richard', 'Ryan', 'Tyler']
const excitedPeople = []

for (let i = 0; i < people.length; i++) {
  excitedPeople[i] = people[i] + '!'
}

This is imperative code, though. We're commanding JavaScript what to do at every single step. We have to give it commands to:

  • set an initial value for the iterator - (let i = 0)
  • tell the for loop when it needs to stop - (i < people.length)
  • get the person at the current position and add an exclamation mark - (people[i] + '!')
  • store the data in the ith position in the other array - (excitedPeople[i])
  • increment the i variable by one - (i++)
  • Declarative Code:

    With declarative code, we don't code up all of the steps to get us to the end result. Instead, we declare what we want to be done, and JavaScript will take care of doing it. This explanation is a bit abstract, so let's look at an example. Let's take the imperative for loop code we were just looking at and refactor it to be more declarative.

    With the imperative code we were performing all of the steps to get to the end result. What is the end result that we actually want, though? Well, our starting point was just an array of names:

    const people = ['Amanda', 'Geoff', 'Michael', 'Richard', 'Ryan', 'Tyler']
    

    The end goal that we want is an array of the same names but where each name ends with an exclamation mark:

    ["Amanda!", "Geoff!", "Michael!", "Richard!", "Ryan!", "Tyler!"]
    

    To get us from the starting point to the end, we'll just use JavaScript's .map() function to declare what we want done.

    const excitedPeople = people.map(name => name + '!')
    

    That's it! Notice that with this code we haven't:

    created an iterator object told the code when it should stop running used the iterator to access a specific item in the people array stored each new string in the excitedPeople array ...all of those steps are taken care of by JavaScript's .map() Array method.

    链接地址: http://www.djcxy.com/p/22876.html

    上一篇: Angular2 innerHtml绑定删除样式属性

    下一篇: React.js中声明式和命令式之间的区别?