React.js 中声明式和命令式的区别?

编程入门 行业动态 更新时间:2024-10-27 14:21:34
本文介绍了React.js 中声明式和命令式的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

最近我一直在研究 Facebook JavaScript 库 React.js 的功能和使用方法.在谈到它与 JavaScript 世界其他部分的差异时,通常会提到两种编程风格 declarative 和 imperative.

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.

两者有什么区别?

推荐答案

声明式风格,就像 react 一样,允许你通过说它应该看起来像这样"来控制应用程序中的流和状态.命令式风格扭转了这一局面,允许您通过说这是您应该做的"来控制您的应用程序.

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.

如果您的管家不知道如何制作鸡肉,那么您就不能以声明式的方式运作.就像如果 Backbone 不知道如何通过变异来完成某项任务一样,你不能只是告诉它来完成那个任务.例如,React 能够是声明性的,因为它知道如何制作鸡肉".相比只知道如何与厨房交互的Backbone.

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.

更多推荐

React.js 中声明式和命令式的区别?

本文发布于:2023-08-06 04:53:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1310183.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:命令   区别   声明   React   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!