Chapter01 Web Development and the FARM Stack
05 The frontend React
FastAPI+React全栈开发05 React前端框架概述
Let’s start with a bit of context here. Perhaps the changes in the world of the web are most visible when we talk about the frontend, the part of the website that is facing the users. Tim Berners Lee made the first HTML. specification public in 1991, and it consisted of text and under 20 tags. In 1994, we got cascading style sheets and the web started looking a little nicer. Legend has it that a new browser scripting language called Mocha was created in just 10 days, that was in 1995. Later, this language went through numerous changes and became what we know today as JavaScript, a powerful and fast language that, with the advent of Node.js, was able to conquer the servers, too.
让我们从这里的一些背景开始。也许当我们谈论前端时,网络世界的变化是最明显的,前端是网站面向用户的部分。蒂姆·伯纳斯·李创造了第一个HTML。规范于1991年公开,它由文本和不到20个标签组成。在1994年,我们有了层叠样式表,网络开始看起来更好一些。传说在1995年,一种叫做Mocha的新的浏览器脚本语言只用了10天就被创造出来了。后来,这种语言经历了无数的变化,成为我们今天所知道的JavaScript,一种强大而快速的语言,随着Node.js的出现,它也能够征服服务器。
Another important concept that has left a strong mark in the development of the frontend is the extensive use of Asynchronous JavaScript and XML(AJAX), you might remember all those rounded corner web apps with vowel based URLs. the technology of making asynchronous HTTP requests was know well before the arrival of Web 2.0 but was mostly underutilized. Libraries such as jQuery, but also Scriptaculous, MooTools, and more, began using AJAX and offering desktop like interactivities in the browser.
另一个在前端开发中留下深刻印记的重要概念是异步JavaScript和XML(AJAX)的广泛使用,你可能还记得那些使用基于元音的url的圆角web应用程序。发出异步HTTP请求的技术在Web 2.0到来之前就已经很有名了,但基本上没有得到充分利用。诸如jQuery、Scriptaculous、MooTools等库开始使用AJAX,并在浏览器中提供类似桌面的交互性。
One propblem that quickly arose was the handling of data across shared views. Backbone, Knockout, and Ember were the most popular libraries that mitigated to solve that problem. In 20010, AngularJS came to light; this was a complex Model View Controller (MVC) based framework with a very specific and prescribed way of doing things.
很快出现的一个问题是跨共享视图处理数据。Backbone、Knockout和Ember是解决这个问题的最流行的库。2010年,AngularJS问世;这是一个复杂的基于模型-视图-控制器(MVC)的框架,具有非常具体和规定的做事方式。
In May 2013, React was presented in the US and the web development world was able to witness numerous innovations, virtual DOM, one-way data flow, the Flux pattern, and more.
2013年5月,React在美国发布,web开发世界见证了许多创新,虚拟DOM,单向数据流,Flux模式等等。
This is bit of history to just try and provide some context and continuity because web development, like any other creative human activity, rarely moves in quantum leaps. Usually, it moves in steps that enable users to resolve the issues that they are facing in an, often, suboptimal way. It would be unfair not to mention Vue.js, which is an excellent choice for building frontends that also sports an entire ecosystem of libraries, and Svelte.js, which offers a radical shift in building UIs in the sense that the UI is compiled and the bundled size is significantly smaller.
这是一段历史,只是试图提供一些背景和连续性,因为网络开发,像任何其他创造性的人类活动一样,很少有巨大的飞跃。通常,它采取步骤,使用户能够以一种通常不是最优的方式解决他们所面临的问题。不提Vue.js和Svelte.js是不公平的,Vue.js是构建前端的绝佳选择,同时也展示了一个完整的库生态系统,Svelte.js在构建UI方面提供了根本性的转变,因为UI是编译的,绑定的大小明显更小。
Why use React
As of 2022, interactive, attractive, fast, and intuitive UIs are a necessity for any public facing web application. It is possible, though very difficult, to achieve most or every functionality that even a simple web is expected to provide using just plain JavaScript. FastAPI is more than capable of serving HTML (and static files, such as JavaScript or CSS) usig any compatible templating engine (the most widely used in the Python world is probably Jinja2), but we and the users want more.
到2022年,交互式、有吸引力、快速和直观的ui将成为任何面向公众的web应用程序的必需品。这是可能的,虽然非常困难,实现大多数或每一个功能,即使是一个简单的web期望提供使用纯JavaScript。FastAPI不仅能够使用任何兼容的模板引擎(Python世界中使用最广泛的可能是Jinja2)提供HTML(和静态文件,如JavaScript或CSS),而且我们和用户还想要更多。
First of all, we want a streamlined and structured way of building UIs. React enables the developers to create dynamic applications in a much easier way by relying on JSX, a mix of JavaScript and XML that has an intuitive tag, based syntax and provides developers with a way to think of the application in terms of components that go on to form other, more complex, components, thus breaking the process of crafting complex user interfaces and interactions into smaller, more manageable steps.
首先,我们想要一种精简和结构化的方式来构建ui。React使开发人员能够通过依赖JSX以一种更简单的方式创建动态应用程序,JSX是JavaScript和XML的混合,具有直观的基于标签的语法,并为开发人员提供了一种从组件的角度来考虑应用程序的方法,这些组件可以继续形成其他更复杂的组件,从而将复杂的用户界面和交互过程分解为更小、更易于管理的步骤。
The main benefits of using React as a frontend solution can be summarized as follows:
- Performance: By using the React virtual DOM, which operates in memory, React apps provide smooth and fast performance.
- Reusability: Since the app is built by using components that have their own properties and logic, we can write out components once and then reuse them as many times as needed, cutting down development time and complexity.
- Ease of use: This is always a bit subjective, but React is easy to get started. Advanced concepts and patterns require some level of proficiency, but even novice developers can reap immediate benefits just from the possibility of splitting the application frontend into components and then using them like LEGO bricks.
- SPAs or SSR: React and frameworks based on React empower us, the developers, to create Single-Page Applications that have a desktop-like look and feel but also server-side rendering that is beneficial for search engine optimization.
- React-based frameworks: Knowing our way around React enables us to benefit from some of today’s most powerful frontend web frameworks such as Next.js, static site generators (such as Gatsby.js), or exciting and promising newcomers (such as React Remix).
- Hooks system: In version 16.8, the React library introduced hooks that enable the developers to use and manipulate the state of the components, along with some other features of React without the need to use classes. This is a big change that tackles (successfully) different issues: it enables the reusability of stateful logic between components and simplifies the understanding and management of complex components.
使用React作为前端解决方案的主要好处可以总结如下:
-
性能:通过使用在内存中运行的React虚拟DOM, React应用程序提供了平滑和快速的性能。
-
可重用性:由于应用程序是通过使用具有自己属性和逻辑的组件构建的,因此我们可以一次编写组件,然后根据需要多次重用它们,从而减少开发时间和复杂性。
-
易用性:这总是有点主观,但React很容易上手。高级概念和模式需要一定程度的熟练程度,但即使是新手开发人员也可以从将应用程序前端拆分为组件的可能性中立即获益,然后像使用乐高积木一样使用它们。
-
spa或SSR: React和基于React的框架使我们开发人员能够创建单页应用程序,这些应用程序具有类似桌面的外观和感觉,但也具有有利于搜索引擎优化的服务器端渲染。
-
基于React的框架:了解React的方法使我们能够受益于当今一些最强大的前端web框架,如Next.js,静态站点生成器(如Gatsby.js),或令人兴奋和有前途的新框架(如React Remix)。
-
Hooks系统:在16.8版本中,React库引入了Hooks,使开发人员能够使用和操作组件的状态,以及React的一些其他功能,而无需使用类。这是一个很大的变化,它(成功地)解决了不同的问题:它支持组件之间有状态逻辑的可重用性,并简化了对复杂组件的理解和管理。
The simplest React hooks is probably the useState hook, it enables us to have and maintain a stateful value (such as an object, array, or variable) throughout the life cycle of the component, without having to resort to old-school class-based components.
最简单的React钩子可能是useState钩子,它使我们能够在组件的整个生命周期中拥有和维护一个有状态的值(比如对象、数组或变量),而不必求助于老派的基于类的组件。
For instance, a very simple component that could be used for filtering search results when a user is trying to find the right car might contain the desired brand, model, and some production year range. This functionality would be a great candidate for a separate component, a search component that would need to maintain the state of different input controls, probably implemented as a series of dropdowns. Let’s just see the simplest possible version of this implementation. We will create a simple functional component with a single stateful string value, an HTML select element that will update the stateful variable named brand.
例如,当用户试图查找合适的汽车时,可以使用一个非常简单的组件来过滤搜索结果,该组件可能包含所需的品牌、型号和某些生产年份范围。这个功能对于一个单独的组件来说是一个很好的选择,一个需要维护不同输入控件状态的搜索组件,可能作为一系列下拉菜单来实现。让我们看看这个实现的最简单的版本。我们将创建一个简单的功能组件,其中包含一个有状态字符串值,一个HTML select元素,用于更新名为brand的有状态变量。
import {useState} from "react"
const Search = () => {
// 响应式变量:品牌
const [brand, setBrand] = useState("")
// 返回JSX内容
return (
<div>
<div>选择品牌:{brand} </div>
<select onChange={e=>setBrand(e.target.value)}>
<option value="">所有品牌</option>
<option value="1">小米</option>
<option value="2">华为</option>
<option value="3">三星</option>
</select>
</div>
)
}
export default Search
The bold line is where the hook magic happens, and it must be within the body of a function. The statement simply creates a new state variable, called brand, and provides us a setter function that can be used inside the component to set the desired value.
粗体行是钩子魔术发生的地方,它必须在函数体中。该语句只是创建了一个名为brand的新状态变量,并为我们提供了一个setter函数,可以在组件内部使用该函数来设置所需的值。
There are many hooks that solve different problems, and in this book, we will go over the fundamental ones. In this example, the state variable brand is available inside the component, and it could be tied to a query string that would enable the API to only return the results that conform to the filter defined by the state variable.
有许多钩子可以解决不同的问题,在本书中,我们将讨论基本的钩子。在本例中,状态变量brand在组件中可用,并且可以将其绑定到一个查询字符串,该查询字符串将使API只返回符合状态变量定义的过滤器的结果。
Declarative views: In React, we do not have to worry about transitions or mutations of the DOM. React handles everything, and the only thing the developer has to do is to declare how the view looks and reacts.
声明性视图:在React中,我们不必担心DOM的转换或突变。React处理一切,开发人员唯一要做的就是声明视图的外观和反应。
No templating language: React practically used JavaScript as a templating language (through JSX), so all you have to know in order to be able to use it effectively is some JavaScript, such as array manipulation and iteration.
没有模板语言:React实际上使用JavaScript作为模板语言(通过JSX),所以为了能够有效地使用它,你所需要知道的只是一些JavaScript,比如数组操作和迭代。
Rich ecosystem: There are numerous excellent libraries that complement React’s basic functionality, from routers to custom hooks, external library integrations, CSS framework adaptations, and more.
丰富的生态系统:有许多优秀的库补充了React的基本功能,从路由器到自定义钩子,外部库集成,CSS框架适配等等。
In this book, we will not dive deep into React. Why not? Well, I believe that the UI is as important as any other part of the app, if your app is not user friendly or downright ugly, nobody will want to have anything to do with it, no matter how much value it brings. However, that is not the emphasis of this book. The idea is just to get the ball rolling and see how all the different parts connect and fit within the bigger picture. So, we will keep the frontend part to a minimum. Another reason to choose React is because of its great community, so you are bound to have to deal with it someday if you haven’t already, and to be quite honest, with the addition of React Hooks, at least for me, it has become very pleasant to work with. Hooks provide React with a new wawy of adding and sharing stateful logic across components and can even replace (in simpler cases) the need for Redux or other external state management libraries. We will make use of the Context API, a React feature that enables us to pass objects and functions down the component tree without the need of passing props through components that do not need it. Coupled with a hook, the useContext hook, it provides a straightforward way of passing and maintaining stateful values in every part of the app. Just being able to create declarative reusable components and parametrize them into functions was what got me interested, treating visual and UI components like functions with a state if you will. Compared to other frameworks, React is small. It isn’t even considered a framework but a library actually, a couple of libraries. Still, it is a mature product with over 10 years of development behind it, created for the needs of Facebook, and the biggest internet companies such as Uber, Twitter, and Airbnb use and rely upon it.
在本书中,我们不会深入探讨React。为什么不呢?我认为UI与应用的其他部分一样重要,如果你的应用不够用户友好或非常丑陋,没有人会想要与它有任何关系,无论它能带来多少价值。然而,这不是本书的重点。我们的想法只是让球滚动起来,看看所有不同的部分是如何连接起来的,并在更大的画面中适应。所以,我们将保持前端部分的最小值。选择React的另一个原因是它有很棒的社区,所以如果你还没有接触过它,那么总有一天你会接触到它。说实话,随着React Hooks的加入,至少对我来说,它已经变得非常愉快了。Hooks为React提供了一种跨组件添加和共享有状态逻辑的新方式,甚至可以取代(在更简单的情况下)对Redux或其他外部状态管理库的需求。我们将使用上下文API,这是一个React特性,它使我们能够在组件树中向下传递对象和函数,而不需要在不需要它的组件中传递道具。再加上一个钩子,即useContext钩子,它提供了一种直接的方式来传递和维护应用程序的每个部分的有状态值。仅仅能够创建声明式可重用组件并将它们参数化为函数就是让我感兴趣的,如果你愿意的话,将视觉和UI组件视为具有状态的函数。与其他框架相比,React很小。它甚至不被认为是一个框架,而是一个库,实际上是几个库。尽管如此,它是一个成熟的产品,有超过10年的发展历史,是为Facebook的需求而创造的,Uber、Twitter和Airbnb等最大的互联网公司都使用并依赖它。
Like FastAPI, which is based on the newest and cooleast Python features and, thus, makes maximum use of what the language has to offer, React uese (although it is not imperative) the newest features of functional JavaScript, ES6, and ES7, particularly when it comes to arrays. As someone said, working with React improves our understanding of JavaScript, and a similar thing could be said of FastAPI and modern Python.
FastAPI基于最新最酷的Python特性,因此最大限度地利用了该语言提供的功能,React使用(尽管不是强制性的)函数式JavaScript、ES6和ES7的最新特性,特别是在数组方面。正如有人所说,使用React可以提高我们对JavaScript的理解,FastAPI和现代Python也是如此。
The final piece of the puzzle will be the choice of a CSS library or framework. In 2022, there are dozens of CSS libraries that play nice with React, ranging from Bootstrap, Material UI, Bulma, and more. Many of these libraries merge with React to become meaningful frameworks of prebuilt customizable and parametrized components. We will use Tailwind CSS as it is simple to set up , all the cool kinds are using it, and it is intuitive once you get the hang of it, but more on that later.
最后一个难题是选择CSS库或框架。在2022年,有几十个CSS库可以很好地与React配合,包括Bootstrap, Material UI, Bulma等等。其中许多库与React合并,成为预构建的可定制和参数化组件的有意义的框架。我们将使用Tailwind CSS,因为它很容易设置,所有很酷的类型都在使用它,一旦你掌握了它的窍门,它就很直观,但稍后会更多。
Keeping the React part to a bare minimum should allow you, the reader, to focus more on the true protagonists of the story, FastAPI and MongoDB and their dance, and easily replace the React part, should you wish todo so, with anything else that rocks your boat, be it Svelte.js, Vue.js, or vanilla handcrafted ECMAScript.
将React部分保持在最低限度应该允许你,读者,更多地关注故事的真正主角,FastAPI和MongoDB以及他们的舞蹈,并且如果你希望这样做,可以轻松替换React部分,用其他任何东西来撼动你的小船,无论是Svelte.js, Vue.js,还是香草手工制作的ECMAScript。
However, you should know that by embracing or, at the very least, learning the basics of React (and Hooks), you are embarking on a wonderful web development adventure that will enable you to use and understand many tools and frameworks built on top of React.
然而,你应该知道,通过拥抱或至少学习React(和Hooks)的基础知识,你正在踏上一段美妙的web开发之旅,这将使你能够使用和理解构建在React之上的许多工具和框架。
Arguably, Next.js is the feature richest server side rendering React framework that enables fast development, filesystem based routing, and more. Gatsby, a React based routing, and more. Gatsby, a React based static site generator, is a great tool for crafting blazingly fast sites and, coupled with a headless CMS, enables us to create simple and streamlined workflows suited for non-technical staff. React Remix seems to be an interesting project, with a lot of the new React features baked in. Lastly, learning one major frontend framework, be it React, Svelte, or Vue, enables you to switch to another much easier one, the problems they are trying to solve are pretty much the same, and the solutions and underlying philosophies have many things in common even if the implementations might differ drastically.
可以说,Next.js是功能最丰富的服务器端渲染React框架,它支持快速开发、基于文件系统的路由等等。Gatsby,一个基于React的路由,等等。Gatsby是一个基于React的静态站点生成器,它是制作极快站点的好工具,加上无头CMS,使我们能够创建适合非技术人员的简单流线型工作流程。React Remix似乎是一个有趣的项目,包含了很多新的React特性。最后,学习一个主要的前端框架,无论是React、Svelte还是Vue,都能让你切换到另一个更容易的框架,它们试图解决的问题几乎是一样的,即使实现可能有很大的不同,解决方案和底层哲学也有很多共同点。