Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

reactjs - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 the kitchen
Open fridge
Remove chicken from fridge
...
Bring food to the table

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

I want 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...