react基础_React基础

react基础

After all my teachings about React, be it online for a larger audience or on-site for companies transitioning to web development and React, I always come to the conclusion that React is all about JavaScript. Newcomers to React but also myself see it as an advantage, because you carry your JavaScript knowledge for a longer time around compared to your React skills.

在我完成所有有关React的教义之后,无论是在线上吸引更多的受众,还是为现场公司过渡到Web开发和React,我总是得出结论,React完全是关于JavaScript的。 React的新手,但我本人也将其视为优势,因为与React技能相比,您持有JavaScript知识的时间更长。

The following walkthrough is my attempt giving you an almost extensive yet concise list about all the different JavaScript functionalities that complement your React knowledge. If you have any other things which are not in the list, just leave a comment for this article and I will keep it up to date.

以下演练是我的尝试,为您提供了关于补充您的React知识的所有不同JavaScript功能的几乎全面而简洁的列表。 如果您还有其他不在列表中的内容,请在本文中发表评论,我将保持最新。

学习Java脚本后输入React (ENTERING REACT AFTER LEARNING JAVASCRIPT)

When you enter the world of React, you are often confronted with a React Class Component:

当您进入React世界时,您经常会遇到React类组件:

In a React class component, there are lots of things to digest for beginners which are not necessarily React: class statements, class methods and inheritance due to being a class. Also JavaScript import statements are only adding complexity when learning React. Even though the main focus point should be JSX (React’s syntax) — everything in the return statement — in the very beginning, often all the things around demand explanations as well. This article is supposed to shed some light into all the things around, most of it JavaScript, without worrying too much about React.

在React类组件中,对于初学者来说,有很多东西需要消化,但不一定是React:类语句,类方法和作为类的继承。 而且,JavaScript导入语句只会在学习React时增加复杂性。 即使主要重点应该是JSX(React的语法)(return语句中的所有内容),从一开始,通常所有周围的内容也需要说明。 这篇文章应该对所有事物(其中大部分是JavaScript)有所了解,而不必过多担心React。

React和JAVASCRIPT类 (REACT AND JAVASCRIPT CLASSES)

Being confronted with a React class component, requires the prior knowledge about JavaScript classes. One would assume that this is given knowledge, but it isn’t, because JavaScript classes are fairly new in the language. Previously, there was only JavaScript’s prototype chain which has been used for inheritance too. JavaScript classes build up on top of the prototypical inheritance giving the whole thing a simpler representation with syntactic sugar.

面对React类组件,需要具备关于JavaScript类的先验知识。 人们会假定这是已知的知识,但事实并非如此,因为JavaScript类在该语言中是相当新的。 以前,只有JavaScript的原型链也已用于继承。 JavaScript类建立在原型继承的基础上,从而使整个事情更容易用语法糖表示。

In order to understand JavaScript classes, you can take some time learning about them without React:

为了理解JavaScript类,您可以花一些时间来学习它们,而无需使用React:

A class describes an entity which is used as a blueprint to create an instance of this entity. Once an instance of the class gets created with the new statement, the constructor of the class is called which instantiates the instance of the class. Therefore, a class can have properties which are usually located in its constructor. In addition, class methods (e.g. getName()) are used to read (or write) data of the instance. The instance of the class is represented as the this object within the class, but outside the instance is just assigned to a JavaScript variable.

类描述了一个实体 ,该实体用作创建该实体的实例的蓝图。 一旦使用new语句创建了类的实例,就将调用该类的构造函数,该实例化该类的实例。 因此,一个类可以具有通常位于其构造函数中的属性。 另外,类方法(例如getName() )用于读取(或写入)实例的数据。 类的实例表示为类内的this对象,但实例外仅分配给JavaScript变量。

Usually classes are used for inheritance in object-oriented programming. They are used for the same in JavaScript whereas the extends statement can be used to inherit with one class from another class. The more specialized class inherits all the abilities from the more general class with the extends statement, and can add its specialized abilities to it:

通常,类用于面向对象编程中的继承。 它们在JavaScript中的用法相同,而extends语句可用于从一个类继承另一个类。 更加专业的类通过extends语句继承了更一般的类的所有功能,并可以为其添加专门的功能:

Basically that’s all it needs to fully understand React class components. A JavaScript class is used for defining a React component, but as you can see, the React component is only a “React component” because it inherits all the abilities from the actual React Component class which is imported from the React package:

基本上,这就是完全理解React类组件所需要的。 JavaScript类用于定义React组件,但是如您所见,React组件只是“ React组件”,因为它继承了从React包导入的实际React Component类的所有功能:

That’s why the render() method is mandatory in React class components: The React Component from the imported React package instructs you to use it for displaying something in the browser. Furthermore, without extending from the React Component, you wouldn't be able to use other lifecycle methods. For instance, there wouldn't be a componentDidMount() lifecycle method, because the component would be an instance of a vanilla JavaScript class. And not only the lifecycle methods would go away, React's API methods such as this.setState() for local state management wouldn't be available as well.

这就是为什么render()方法在React类组件中是强制性的原因:导入的React包中的React Component指示您使用它在浏览器中显示内容。 此外,如果没有从React Component扩展,您将无法使用其他生命周期方法 。 例如,将没有componentDidMount()生命周期方法,因为该组件将是普通JavaScript类的实例。 而且不仅生命周期方法会消失, this.setState()用于本地状态管理的React的API方法(例如this.setState()也将不可用。

However, as you have seen, using a JavaScript class is beneficial for extending the general class with your specialized behavior. Thus you can introduce your own class methods or properties.

但是,正如您所看到的,使用JavaScript类对于通过常规行为扩展通用类是有益的。 因此,您可以介绍自己的类方法或属性。

Now you know why React uses JavaScript classes for defining React class components. They are used when you need access to React’s API (lifecycle methods, this.state and this.setState()). In the following, you will see how React components can be defined in a different way without using a JavaScript class.

现在您知道了为什么React使用JavaScript类来定义React类组件。 当您需要访问React的API(生命周期方法, this.statethis.setState() )时,可以使用它们。 在下面,您将看到如何在不使用JavaScript类的情况下以不同的方式定义React组件。

After all, JavaScript classes welcome one using inheritance in React, which isn’t a desired outcome for React, because React favors composition over inheritance. So the only class you should extend from your React components should be the official React Component.

毕竟,JavaScript类欢迎在React中使用继承的类,这对React来说并不是理想的结果, 因为React偏爱继承而不是继承 。 因此,您应该从React组件扩展的唯一类应该是官方的React Component。

React中的箭头功能 (ARROW FUNCTIONS IN REACT)

When teaching someone about React, I explain JavaScript arrow functions pretty early. They are one of JavaScript’s language additions in ES6 which pushed JavaScript forward in functional programming.

在教某人有关React的知识时,我很早就解释了JavaScript箭头功能 。 它们是ES6中JavaScript语言的新增功能之一,这在功能编程中推动了JavaScript的发展。

JavaScript arrow functions are often used in React applications for keeping the code concise and readable. I love them, teach them early, but always try to refactor my functions from JavaScript ES5 to ES6 functions along the way. At some point, when the differences between JavaScript ES5 functions and JavaScript ES6 functions become clear, I stick to the JavaScript ES6 way of doing it with arrow functions. However, I always see that too many different syntaxes can be overwhelming for React beginners. So I try to make the different characteristics of JavaScript functions clear before going all-in using them in React. In the following sections, you will see how JavaScript arrow functions are commonly used in React.

React应用程序中经常使用JavaScript箭头函数来保持代码的简洁和可读性。 我喜欢它们,尽早教他们,但始终尝试将我的功能从JavaScript ES5重构为ES6函数。 在某个时候,当JavaScript ES5函数和JavaScript ES6函数之间的区别变得很明显时,我会坚持使用JavaScript ES6的箭头函数来完成此操作。 但是,我总是看到,对于React初学者来说,太多不同的语法可能会让人不知所措。 因此,在尝试在React中全面使用JavaScript函数之前,我会尝试弄清楚它们的不同特性。 在以下各节中,您将看到React常用JavaScript箭头功能。

It’s a function which receives an input (e.g. props) and returns the displayed HTML elements (view). Under the hood, the function only needs to use the rendering mechanism of the render() method from React components:

这个函数接收输入(例如props )并返回显示HTML元素(视图)。 在幕后,该函数仅需要使用React组件中的render()方法的呈现机制:

Function components are the preferred way of defining components in React. They have less boilerplate, add less complexity, and are simpler to maintain than React class components. You can easily migrate your class components to function components with React Hooks.

功能组件是在React中定义组件的首选方式。 与React类组件相比,它们具有更少的样板,增加了更少的复杂性,并且易于维护。 您可以使用React Hooks轻松地将类组件迁移到功能组件。

Previously, the article mentioned JavaScript arrow functions and how they improve your React code. Let’s apply these kind of functions to your function components. The previous Greeting component has two different looks with JavaScript ES5 and ES6:

之前,文章提到了JavaScript箭头功能以及它们如何改善React代码。 让我们将这类功能应用于功能组件。 先前的Greeting组件在JavaScript ES5和ES6中具有两种不同的外观:

JavaScript arrow functions are a great way of keeping your function components in React concise. Even more when there is no computation in between and thus the function body and return statement can be left out.

JavaScript箭头函数是使函数组件保持简洁的一种好方法。 当两者之间没有计算时,甚至更多,因此可以省去函数体和return语句。

React类组件语法 (REACT CLASS COMPONENT SYNTAX)

React’s way of defining components evolved over time. In its early stages, the React.createClass() method was the default way of creating a React class component. Nowadays, it isn't used anymore, because with the rise of JavaScript ES6, the previously used React class component syntax became the default (only before React function components were introduced).

随着时间的推移,React定义组件的方式不断发展。 在早期, React.createClass()方法是创建React类组件的默认方法。 如今,它不再使用了,因为随着JavaScript ES6的兴起,以前使用的React类组件语法成为默认语法(仅在引入React函数组件之前)。

However, JavaScript is evolving constantly and thus JavaScript enthusiast pick up new ways of doing things all the time. That’s why you will find often different syntaxes for React class components. One way of defining a React class component, with state and class methods, is the following:

但是,JavaScript一直在不断发展,因此JavaScript爱好者一直在寻找新的做事方式。 这就是为什么您会发现React类组件经常使用不同的语法的原因。 定义带有状态和类方法的React类组件的一种方法如下:

However, when implementing lots of React class components, the binding of class methods in the constructor — and having a constructor in the first place — becomes a tedious implementation detail. Fortunately, there is a shorthand syntax for getting rid of both:

但是,当实现许多React类组件时,构造函数中类方法的绑定(首先是构造函数)成为一个乏味的实现细节。 幸运的是,有一种简化的语法可以消除这两种情况:

By using JavaScript arrow functions, you can auto-bind class methods without having to bind them in the constructor. Also the constructor can be left out, when not using the props, by defining the state directly as a class property.

通过使用JavaScript箭头函数,您可以自动绑定类方法,而不必在构造函数中绑定它们。 当不使用道具时,也可以通过直接将状态定义为类属性来省去构造函数。

Note: Be aware that class properties are not in the JavaScript language yet.) Therefore you can say that this way of defining a React class component is way more concise than the other version.

注意:请注意, 类属性 尚未使用JavaScript语言。)因此,您可以说,这种定义React类组件的方法比其他版本更简洁。

React中的模板文字 (TEMPLATE LITERALS IN REACT)

Template literals are another JavaScript language specific feature that came with JavaScript ES6. It is worth to mention it shortly, because when people new to JavaScript and React see them, they can be confusing as well. When learning JavaScript, it’s the following syntax that you grow up with for concatenating a string:

模板文字是JavaScript ES6随附的另一种JavaScript语言特定功能。 值得一提的是,因为刚接触JavaScript和React的人看到他们时,他们也会感到困惑。 学习JavaScript时,会使用以下语法来连接字符串:

Template literals can be used for the same which is called string interpolation:

模板文字可用于相同的东西,称为字符串插值:

You only have to use backticks and the ${} notation for inserting JavaScript primitives. However, string literals are not only used for string interpolation, but also for multiline strings in JavaScript:

您只需使用反引号和${}表示法来插入JavaScript原语。 但是,字符串文字不仅用于字符串插值,而且还用于JavaScript中的多行字符串:

Basically that’s how larger text blocks can be formatted on multiple lines. For instance, it can be seen with the recent introduction of GraphQL in JavaScript, because GraphQL queries are composed with template literals. Also React Styled Components makes use of template literals.

基本上,这就是大文本块可以多行格式化的方式。 例如,最近在JavaScript中引入GraphQL可以看出这一点,因为GraphQL查询由模板文字组成。 React Styled Components也使用模板文字。

映射,减少和过滤实际 (MAP, REDUCE AND FILTER IN REACT)

What’s the best approach teaching the JSX syntax for React beginners? Usually I start out with defining a variable in the render() method and using it as JavaScript in HTML in the return block.

为React初学者教授JSX语法的最佳方法是什么? 通常,我首先在render()方法中定义一个变量,然后在return块中将其用作HTML中JavaScript。

You only have to use the curly braces to get your JavaScript in HTML. Going from rendering a string to a complex object isn’t any different

您只需要使用花括号就可以用HTML获得JavaScript。 从渲染字符串到复杂的对象没有什么不同

Usually the next question then is: How to render a list of items? That’s one of the best parts about explaining React in my opinion. There is no React specific API such as a custom attribute on a HTML tag which enables you to render multiple items in React. You can use plain JavaScript for iterating over the list of items and returning HTML for each item.

通常,接下来的问题是:如何呈现项目列表? 我认为这是解释React的最好部分之一。 没有特定于React的API,例如HTML标记上的自定义属性,使您可以在React中呈现多个项目。 您可以使用普通JavaScript遍历项目列表并为每个项目返回HTML。

Having used the JavaScript arrow function before, you can get rid of the arrow function body and the return statement which leaves your rendered output way more concise.

之前使用过JavaScript的箭头函数,您可以摆脱箭头函数的主体和return语句,这使呈现的输出方式更加简洁。

Pretty soon, every React developer becomes used to the built-in JavaScript map() methods for arrays. It just makes so much sense to map over an array and return the rendered output for each item. The same can be applied for custom tailored cases where filter() or reduce() make more sense rather than rendering an output for each mapped item.

很快,每个React开发人员都习惯了数组的内置JavaScript map()方法。 映射数组并返回每个项目的渲染输出非常有意义。 同样的情况也适用于定制的情况,其中filter()reduce()更具意义,而不是为每个映射的项呈现输出。

In general, that’s how React developers are getting used to these JavaScript built-in functions without having to use a React specific API for it. It is just JavaScript in HTML.

通常,这就是React开发人员习惯于这些JavaScript内置函数的方式,而不必为此使用React特定的API。 它只是HTML中JavaScript。

VAR,LET和CONST的React (VAR, LET, AND CONST IN REACT)

Also the different variable declarations with var, let and const can be confusing for beginners to React even though they are not React specific. Maybe it is because JavaScript ES6 was introduced when React became popular. In general, I try to introduce let and const very early in my workshops. It simply starts with exchanging var with const in a React component:

同样,带有varletconst的不同变量声明也可能使初学者对React感到困惑,即使他们不是特定于React的。 也许是因为React流行时引入了JavaScript ES6。 总的来说,我会在我的工作室中尽早介绍letconst 。 它只是从在React组件中用const交换var开始:

Then I give the rules of thumb when to use which variable declaration:

然后,我给出了何时使用哪个变量声明的经验法则:

  • (1) don’t use var anymore, because let and const are more specific

    (1)不再使用var ,因为letconst更具体

  • (2) default to const, because it cannot be re-assigned or re-declared

    (2)默认为const ,因为它不能重新分配或重新声明

  • (3) use let when re-assigning the variable

    (3)在重新分配变量时使用let

While let is usually used in a for loop for incrementing the iterator, const is normally used for keeping JavaScript variables unchanged. Even though it is possible to change the inner properties of objects and arrays when using const, the variable declaration shows the intent of keeping the variable unchanged though.

let通常在for循环中用于递增迭代器,而const通常用于使JavaScript变量保持不变。 尽管使用const可以更改对象和数组的内部属性,但是变量声明显示了保持变量不变的意图。

三元运算符 (TERNARY OPERATOR IN REACT)

But it doesn’t end with displaying JavaScript strings, objects, and arrays in React. What about an if-else statement for enabling conditional rendering? You cannot use an if-else statement directly in JSX, but you can return early from the rendering function. Returning null is valid in React when displaying nothing.

但这并没有以在React中显示JavaScript字符串,对象和数组结尾。 如果启用条件渲染的if-else语句呢? 您不能直接在JSX中使用if-else语句,但可以尽早从渲染函数返回。 不显示任何内容时,在React中返回null是有效的。

However, if you want to use an if-else statement within the returned JSX, you can do it by using a JavaScripts ternary operator:

但是,如果要在返回的JSX中使用if-else语句,则可以通过使用JavaScripts三元运算符来实现 :

Another way of doing it, if you only return one side of the conditional rendering anyway, is using the && operator:

如果仍然只返回条件渲染的一侧,则另一种方法是使用&&运算符:

I will not go into detail why this works, but if you are curious, you can learn about it and other techniques for conditional rendering over here: All the conditional renderings in React. After all, the conditional rendering in React only shows again that most of React is only JavaScript in JSX and not anything React specific.

我不会详细说明它为什么起作用,但是如果您好奇的话,可以在这里了解它以及其他条件渲染技术:React中的所有条件渲染。 毕竟,React中的条件渲染仅再次表明,大多数React只是JSX中JavaScript,而不是任何特定的React。

实际执行的进出口声明 (IMPORT AND EXPORT STATEMENTS IN REACT)

Fortunately, the JavaScript community settled on one way to import and export functionalities from files with JavaScript ES6 with import and export statements.

幸运的是,JavaScript社区决定采用一种通过具有导入和导出语句JavaScript ES6从文件导入和导出功能的方法。

However, being new to React and JavaScript ES6, these import and export statements are just another topic which requires explanation when getting started with your first React application. Pretty early you will have your first imports for CSS, SVG or other JavaScript files. The create-react-app project already starts with those import statements:

但是,对于React和JavaScript ES6来说,这些导入和导出语句只是另一个主题,在开始使用第一个React应用程序时,需要进行解释。 很快,您将首次导入CSS,SVG或其他JavaScript文件。 create-react-app项目已经从这些import语句开始:

It’s great for the starter project, because it offers you a well-rounded experience how other files can be imported and (exported). Also the App component gets imported in the src/index.js file. However, when doing your first steps in React, I try to avoid those imports in the beginning. Instead, I try to focus on JSX and React components. Only later the import and export statements are introduced when separating the first React component or JavaScript function in another file.

这对于入门项目非常有用,因为它为您提供了如何导入和导出其他文件的全面体验。 同样,App组件也被导入到src / index.js文件中。 但是,当您在React中迈出第一步时,我尝试一开始避免这些导入。 相反,我尝试着重于JSX和React组件。 仅在以后将导入第一个React组件或JavaScript函数到另一个文件中时,才引入import和export语句。

So how do these import and export statements work? Let’s say in one file you want to export the following variables:

那么这些导入和导出语句如何工作? 假设您要在一个文件中导出以下变量:

const firstname = 'DINESH';const lastname = 'Ko';export { firstname, lastname };

Then you can import them in another file with a relative path to the first file

然后,您可以将它们导入另一个文件,该文件具有第一个文件的相对路径

import { firstname, lastname } from './file1.js';console.log(firstname);// output: DINESH

So it’s not necessarily about importing/exporting components or functions, it’s about sharing everything that is assignable to a variable (leaving out CSS or SVG imports/exports, but speaking only about JS). You can also import all exported variables from another file as one object:

因此,这不一定与导入/导出组件或功能有关,而是与共享可分配给变量的所有内容(省去CSS或SVG导入/导出,而只讲JS)。 您还可以将来自另一个文件的所有导出变量导入为一个对象:

import * as person from './file1.js';console.log(person.firstname);// output: DIENSH

Imports can have an alias. It can happen that you import functionalities from multiple files that have the same named export. That’s why you can use an alias:

导入可以具有别名。 您可能会从具有相同命名导出功能的多个文件中导入功能。 这就是为什么您可以使用别名的原因:

import { firstname as username } from './file1.js';console.log(username);// output: DINESH

All the previous cases are named imports and exports. But there exists the default statement too. It can be used for a few use cases:

先前所有案例均被命名为进出口。 但是也存在默认语句。 它可以用于一些用例:

  • to export and import a single functionality

    导出和导入单个功能
  • to highlight the main functionality of the exported API of a module

    突出显示模块导出的API的主要功能
  • to have a fallback import functionality

    具有后备导入功能
const dinesh= {firstname: 'DINESH',lastname: 'KO',};export default dinesh;

Leave out the curly braces for the import to import the default export:

省略用于导入的花括号以导入默认导出:

import developer from './file1.js';console.log(developer);// output: { firstname: 'DINESH', lastname: 'KO' }

Furthermore, the import name can differ from the exported default name. You can also use it in conjunction with the named export and import statements:

此外,导入名称可以与导出的默认名称不同。 您也可以将其与命名的export和import语句结合使用:

const firstname = 'DINESH';const lastname = 'ko';const person = {firstname,lastname,};export {firstname,lastname,};export default person;

And import the default or the named exports in another file:

并将默认或命名的导出导入另一个文件:

import developer, { firstname, lastname } from './file1.js';console.log(developer);// output: { firstname: 'DINESH', lastname: 'KO' }console.log(firstname, lastname);// output: DINESH KO

You can also spare additional lines and export the variables directly for named exports:

您还可以保留其他行,并直接将变量导出以用于命名的导出:

export const firstname = 'DINESH';export const lastname = 'Ko';

These are the main functionalities for ES6 modules. They help you to organize your code, to maintain your code, and to design reusable module APIs. You can also export and import functionalities to test them.

这些是ES6模块的主要功能。 它们可帮助您组织代码,维护代码以及设计可重用的模块API。 您还可以导出和导入功能以对其进行测试。

React中的图书馆 (LIBRARIES IN REACT)

React offers state management and side-effect features, but apart from this, it is only a component library which renders HTML for your browser. Everything else can be added from APIs (e.g. browser API, DOM API), JavaScript functionalities (e.g. map, filter, reduce) or external libraries. It’s not always simple to choose the right library for complementing your React application, but once you have a good overview of the different options, you can pick the one which fits best to your tech stack.

React提供了状态管理和副作用功能,但除此之外,它只是一个为您的浏览器呈现HTML的组件库。 其他所有内容都可以从API(例如浏览器API,DOM API),JavaScript功能(例如映射,过滤,缩小)或外部库中添加。 选择合适的库来补充您的React应用程序并不总是那么简单,但是一旦您对不同的选择有了一个很好的了解,就可以选择最适合您的技术堆栈的一个。

For instance, fetching data in React can be done with the native fetch API:

例如,可以使用本机获取API在React中获取数据:

But it is up to you to use another library to fetch data in React. Axios is one popular choice for React applications

但是由您决定使用另一个库来在React中获取数据。 Axios是React应用程序的一种流行选择

So once you know about your problem which needs to be solved, React’s extensive and innovative ecosystem should give you plenty of options solving it. There again it’s not about React, but knowing about all the different JavaScript libraries which can be used to complement your application.

因此,一旦您知道需要解决的问题, React广泛而创新的生态系统便会为您提供大量解决方案。 再说一遍,这不是关于React,而是了解可用于补充您的应用程序的所有不同JavaScript库。

异步/等待React (ASYNC/AWAIT IN REACT)

In a React Function Component, fetching data looks slightly different with React Hooks:

在React函数组件中,使用React Hooks来获取数据看起来有些不同:

In the previous code snippet, we have used the most common way to resolve a promise with a then-block. The catch-block for error handling is missing for keeping the example simple. Please read one of the referenced tutorials to learn more about fetching data in React with error handling.

在前面的代码片段中,我们使用了最常见的方式来使用then块来解决promise。 为了简化示例,缺少用于错误处理的catch块。 请阅读参考的教程之一,以了解有关使用错误处理在React中获取数据的更多信息。

Anyway, you can also use async/await which got introduced to JavaScript not long ago:

无论如何,您还可以使用不久前引入JavaScript的async / await:

In the end, async/await is just another way of resolving promises in asynchronous JavaScript.

最后,异步/等待只是异步JavaScript中解决承诺的另一种方法。

React中的高阶函数 (HIGHER-ORDER FUNCTIONS IN REACT)

Higher-order functions are a great programming concept especially when moving towards functional programming. In React, it makes total sense to know about these kind of functions, because at some point you have to deal with higher-order components which can be explained best when knowing about higher-order functions in the first place.

高阶函数是一个很好的编程概念,尤其是在进行函数编程时。 在React中,了解这类功能是完全有意义的,因为在某些时候,您必须处理高阶组件,而这些组件首先应在了解高阶函数时得到最好的解释。

Higher-order functions can be showcased in React early on without introducing higher-order components. For instance, let’s say a rendered list of users can be filtered based on the value of an input field.

无需引入高阶组件即可在React早期展示高阶函数。 例如,假设可以根据输入字段的值来过滤呈现的用户列表。

It’s not always desired to extract functions, because it can add unnecessary complexity, but on the other side, it can have beneficial learning effects for JavaScript. In addition, by extracting a function you make it testable in isolation from the React component. So let’s showcase it with the function which is provided to the built-in filter function.

并非总是希望提取函数,因为它会增加不必要的复杂性,但另一方面,它可能会对JavaScript产生有益的学习效果。 另外,通过提取一个函数,可以使其与React组件隔离地进行测试。 因此,让我们用内置过滤器功能提供的功能对其进行展示。

The previous implementation doesn’t work because the doFilter() function needs to know about the query property from the state. So you can pass it to the function by wrapping it with another function which leads to a higher-order function.

先前的实现无效,因为doFilter()函数需要从状态中了解query属性。 因此,您可以通过将其包装到另一个导致高阶函数的函数来将其传递给函数。

Basically a higher-order function is a function which returns a function. By using JavaScript ES6 arrow functions, you can make a higher-order function more concise. Furthermore, this shorthand version makes it more attractive composing functions into functions

基本上,高阶函数是返回函数的函数。 通过使用JavaScript ES6箭头函数,可以使高阶函数更简洁。 此外,该速记版本使将函数组合成函数更具吸引力

const doFilter = query => user =>user.name.includes(query);

Now, the doFilter() function can be exported from the file and tested in isolation as pure (higher-order) function. After learning about higher-order functions, all the fundamental knowledge is established to learn more about React's higher-order components, if you want to learn about this advanced technique in React. Moving functions around your code base is a great way to learn about the benefits of having functions as first class citizens in JavaScript. It's powerful when moving your code towards functional programming.

现在,可以从文件中导出doFilter()函数,并作为纯(高阶)函数进行隔离测试。 在学习了高阶函数之后,如果您想了解React中的这一高级技术,便可以建立所有基本知识,以进一步了解React的高阶组件。 在代码库中移动函数是了解使用JavaScript作为一流公民的好处的好方法。 在将代码移向函数式编程时,它功能强大。

短期对象分配 (SHORTHAND OBJECT ASSIGNMENT)

There is one little addition in the JavaScript language which leaves beginners confused. In JavaScript ES6, you can use a shorthand property syntax to initialize your objects more concisely, like following object initialization:

JavaScript语言中有一点新增功能,使初学者感到困惑。 在JavaScript ES6中,您可以使用简写属性语法来更简洁地初始化对象,例如以下对象初始化:

const name = 'Dinesh';const user = {name: name,};

When the property name in your object is the same as your variable name, you can do the following:

当对象中的属性名称与变量名称相同时,可以执行以下操作:

const name = 'Dinesh';const user = {name,};

Shorthand method names are also useful. In JavaScript ES6, you can initialize methods in an object more concisely:

速记方法名称也很有用。 在JavaScript ES6中,您可以更简洁地初始化对象中的方法:

Finally, you are allowed to use computed property names in JavaScript ES6:

最后,允许您在JavaScript ES6中使用计算的属性名称:

You are able to use computed property names to allocate values by key in an object dynamically, a handy way to generate lookup tables (also called dictionaries) in JavaScript.

您可以使用计算出的属性名称通过对象中的键动态分配值,这是在JavaScript中生成查找表(也称为字典)的便捷方法。

实际销毁 (DESTRUCTURING IN REACT)

Another language feature introduced in JavaScript is called destructuring. It’s often the case that you have to access plenty of properties from your state or props in your component. Rather than assigning them to a variable one by one, you can use destructuring assignment in JavaScript.

JavaScript中引入的另一种语言功能称为解构 。 通常,您必须从状态或组件中的道具访问大量属性。 您可以在JavaScript中使用解构分配,而不必将它们一个接一个地分配给变量。

That’s especially beneficial for React’s Function Components, because they always receive the props object in their function signature. Often you will not use the props but only its content, so you can destructure the content in the function signature.

这对于React的功能组件特别有利,因为它们始终在其功能签名中接收props对象。 通常,您不会使用道具,而只会使用道具的内容,因此您可以在函数签名中分解内容。

The destructuring works for JavaScript arrays too:

分解也适用于JavaScript数组:

As you have already seen, React Hooks are using the array destructuring to access state and state updater function.

如您所见,React Hooks正在使用数组解构来访问状态和状态更新程序功能。

Another great feature is the rest destructuring. It is often used for splitting out a part of an object, but keeping the remaining properties in another object.

另一个很大的特点是其余的解构 。 它通常用于拆分对象的一部分,但将其余属性保留在另一个对象中。

Afterward, the list can be used to be rendered, for instance in a React component, whereas the remaining state (here counter) is used somewhere else. That's where the JavaScript spread operator comes into play to forward the rest object to the next component. In the next section, you will see this operator in action.

之后,该列表可用于呈现,例如在React组件中,而其余状态(此处为counter )则用于其他位置。 这就是JavaScript传播运算符发挥作用的地方, 它将其余对象转发到下一个组件。 在下一部分中,您将看到此运算符的作用。

传播操作员的React (SPREAD OPERATOR IN REACT)

The spread operator comes with three …, but shouldn’t be mistaken for the rest operator. It depends on the context where it is used. Used within a destructuring (see above), it is as rest operator. Used somewhere else it is a spread operator.

点差运算符带有三个…,但不要误认为其余运算符。 它取决于使用它的上下文。 在解构结构中使用(请参见上文),它作为rest运算符。 在其他地方使用,它是一个传播算子。

The spread operator literally spreads all the key value pairs of an object. In React, it comes in handy when props are just being passed down to the next component.

扩展运算符从字面上扩展对象的所有键值对。 在React中,当props向下传递到下一个组件时,它会派上用场。

Rather than passing all properties of an object property by property, you can use the spread operator to pass all key value pairs to the next component.

您可以使用传播运算符将所有键值对传递给下一个组件,而不是逐个传递对象属性的所有属性。

Often people say that learning React has a steep learning curve. But it hasn’t when only leaving React in the equation and leaving all the JavaScript out of it. React doesn’t add any foreign abstraction layer on top as other web frameworks are doing it. Instead you have to use JavaScript. So hone your JavaScript skills and you will become a great React developer.

人们通常说学习React具有陡峭的学习曲线。 但是,当仅在方程式中保留React并保留所有JavaScript时,它就没有了。 与其他Web框架一样,React不会在其顶部添加任何外部抽象层。 相反,您必须使用JavaScript。 因此,磨练您JavaScript技能,您将成为一名出色的React开发人员。

翻译自: https://medium.com/swlh/react-fundamentals-4a66e0a66563

react基础

你可能感兴趣的:(python,人工智能,java)