In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "how to learn JavaScript well". In the operation of actual cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Learn JavaScript before starting React
When you start to enter the world of React, create-react-app (https://github.com/facebook/create-react-app) is usually your React project. After building the project, you will see the following React class component:
Import React, {Component} from 'react'; import logo from'. / logo.svg'; import'. / App.css'; class App extends Component {render () {return (
Welcome to React To get started, edit src/App.js and save to reload.
);} export default App
React class components may not be the starting point for *. Beginners have a lot to digest, not necessarily related to React: class statements, class methods, and inheritance. Import statements also add additional complexity when learning React. Although the main focus should be on JSX (the syntax of React), there are other things that need to be explained. This article is mainly aimed at JavaScript, so please don't worry too much about React.
React and JavaScript classes
With regard to React class components, you need to use a priori knowledge about the JavaScript class. The concept of the JavaScript class is relatively new. Previously, only JavaScript's prototype chain could be used to implement inheritance. The JavaScript class is based on prototype inheritance, which makes the inheritance system simpler.
One way to define React components is to use the JavaScript class.
Class Developer {constructor (firstname, lastname) {this.firstname = firstname; this.lastname = lastname;} getName () {return this.firstname +'+ this.lastname;}} var me = new Developer ('Robin',' Wieruch'); console.log (me.getName ())
A class describes an entity that is used to create an instance of the entity. When you create an instance of a class using the new statement, the constructor of the class is called. The properties of a class are usually located in the constructor. In addition, class methods, such as getName (), are used to read (or write) the data of the instance. An instance of a class is represented in the class using a this object, but on the outside, it is only assigned to the JavaScript variable.
In object-oriented programming, classes are usually used to implement inheritance. As in JavaScript, the extends statement can be used to make one class inherit another. A subclass inherits all the functions of a parent class through an extends statement, and can add its own functions.
Class Developer {constructor (firstname, lastname) {this.firstname = firstname; this.lastname = lastname;} getName () {return this.firstname +'+ this.lastname;}} class ReactDeveloper extends Developer {getJob () {return 'ReactDeveloper';}} var me = new ReactDeveloper ('Robin',' Wieruch'); console.log (me.getName ()); console.log (me.getJob ())
Basically, this is all you need to understand the class components of React. The JavaScript class is used to define the React component, which inherits all the functionality of the React Component class imported from the React package.
Import React, {Component} from 'react'; class App extends Component {render () {return (Welcome to React);}} export default App
This is why the render () method is required in the React class component: React Component imported from the React package uses it to display something in the browser. In addition, if you do not inherit from React Component, you will not be able to use other lifecycle methods, including the render () method. For example, if you don't inherit, the componentDidMount () lifecycle method doesn't exist, because now this class is just an instance of a normal JavaScript class. In addition to the unavailable lifecycle methods, React's API methods (such as this.setState () for local state management) are also unavailable.
We can extend the behavior of generic classes through the JavaScript class. Therefore, we can introduce our own class methods or properties.
Import React, {Component} from 'react'; class App extends Component {getGreeting () {return' Welcome to React';} render () {return ({this.getGreeting ()});} export default App
Now you should know why React uses the JavaScript class to define React class components. You can use them when you need to access React's API (lifecycle methods, this.state, and this.setState ()). Next, you'll see how to define React components in different ways, such as not using JavaScript classes, because sometimes you may not need to use class methods, lifecycle methods, or states.
Although we can use JavaScript class inheritance in React, this is not an ideal result for React, because React prefers composition to inheritance. Therefore, the only class that your React component needs to extend should be React Component.
Arrow function in React
When I train people on React, I explain the arrow function of JavaScript to them from the beginning. The arrow function is one of the new language features of ES6 that brings JavaScript one step closer to functional programming.
/ / JavaScript ES5 function function getGreeting () {return 'Welcome to JavaScript';} / / JavaScript ES6 arrow function with body const getGreeting = () = > {return' Welcome to JavaScript';} / / JavaScript ES6 arrow function without body and implicit return const getGreeting = () = > 'Welcome to JavaScript'
The JavaScript arrow function is usually used in React applications to keep the code concise and readable. I love arrowhead functions and always try to reconstruct my functions from JavaScript ES5 to ES6. At some point, I use the arrow function of JavaScript ES6 when the difference between the JavaScript ES5 function and the JavaScript ES6 function is obvious. However, for newcomers to React, too many different grammars can be overwhelming. So, before using them in React, I'll try to explain the different characteristics of JavaScript functions. In the following sections, you will learn how to use the JavaScript arrow function in React.
Treat a function as a component in React
React uses different programming paradigms, thanks to JavaScript being a "generalist" programming language. In terms of object-oriented programming, React's class components can make good use of JavaScript classes (inheritance, class methods, and class properties of React component API, such as this.state). On the other hand, React (and its ecosystem) also uses many concepts of functional programming. For example, React's function stateless component is another way to define React components. So what if you could use a component like a function?
Function (props) {return view;}
This is a function that takes input (such as props) and returns a HTML element (view). It does not need to manage any state (stateless), nor does it need to know any methods (class methods, lifecycle methods). This function only needs to be rendered using the render () method of the React component.
Function Greeting (props) {return {props.greeting};}
Functional stateless components are methods that define components in React. They have less boilerplate code, less complexity, and are easier to maintain than React class components. However, both have their own reasons for existence.
Having mentioned the JavaScript arrow functions and their ability to improve the readability of the code, let's apply these functions to stateless components. The previous Greeting components were written a little differently in JavaScript ES5 and ES6:
/ / JavaScript ES5 function function Greeting (props) {return {props.greeting};} / JavaScript ES6 arrow function const Greeting = (props) = > {return {props.greeting};} / / JavaScript ES6 arrow function without body and implicit return const Greeting = (props) = > {props.greeting}
The JavaScript arrow function is a good way to keep React stateless components concise.
React class component syntax
The way React defines components has been evolving. In the early stages, the React.createClass () method was the default way to create React class components. This method is no longer used because with the rise of JavaScript ES6, the previous React class component syntax became the default syntax.
However, JavaScript is also evolving, so JavaScript enthusiasts are always looking for new ways. This is why you will find that React class components use different syntax. One way to define React class components using state and class methods is as follows:
Class Counter extends Component {constructor (props) {super (props); this.state = {counter: 0,}; this.onIncrement = this.onIncrement.bind (this); this.onDecrement = this.onDecrement.bind (this);} onIncrement () {this.setState (state = > ({counter: state.counter + 1}) } onDecrement () {this.setState (state = > ({counter: state.counter-1}));} render () {return (
{this.state.counter}
Increment Decrement);}}
However, when implementing a large number of React class components, the class method binding in the constructor and the constructor itself become tedious implementation details. Fortunately, there is a short grammar that can be used to get rid of these two worries:
Class Counter extends Component {state = {counter: 0,}; onIncrement = () = > {this.setState (state = > ({counter: state.counter + 1}));} onDecrement = () = > {this.setState (state = > ({counter: state.counter-1}));} render () {return (
{this.state.counter}
Increment Decrement);}}
By using the JavaScript arrow function, you can bind class methods automatically without having to bind them in the constructor. By defining the state directly as a class attribute, the constructor can be omitted when not using props. Note: note that JavaScript does not support class attributes yet. Therefore, you can say that this way of defining React class components is more concise than other versions.
Template literals in React
Template literals are another JavaScript language feature that comes with JavaScript ES6. This feature is mentioned because newcomers to JavaScript and React may be confused when they see them. Take the syntax of the following connection string as an example:
Function getGreeting (what) {return 'Welcome to' + what;} const greeting = getGreeting ('JavaScript'); console.log (greeting); / / Welcome to JavaScript
The literal amount of the template can be used for the same purpose, called string interpolation:
Function getGreeting (what) {return `Welcome to ${what} `;}
You just need to use backquotes and ${} to insert the JavaScript primitive. String literals can be used not only for string interpolation, but also for multiline strings:
Function getGreeting (what) {return `Welcome to ${what} `;}
This allows you to format multiline blocks of text.
Map, Reduce and Filter in React
When teaching JSX syntax to a novice to React, I usually define a variable in the render () method and then use it in the return code block.
Import React, {Component} from 'react'; class App extends Component {render () {var greeting =' Welcome to React'; return ({greeting});}} export default App
You only need to use curly braces to manipulate JavaScript in HTML. It doesn't make much difference whether it's rendering a string or rendering a complex object.
Import React, {Component} from 'react'; class App extends Component {render () {var user = {name:' Robin'}; return ({user.name});}} export default App
The next question is: how to render the project list? React does not provide a specific API, such as the custom attribute of the HTML tag, for rendering the project list. We can use pure JavaScript code to iterate over the list of projects and return the HTML for each project.
Import React, {Component} from 'react'; class App extends Component {render () {var users = [{name:' Robin'}, {name: 'Markus'},]; return ({users.map (function (user) {return {user.name};})});} export default App
By using the JavaScript arrow function, you can get rid of the arrow function body and return statements to make the rendered output more concise.
Import React, {Component} from 'react'; class App extends Component {render () {var users = [{name:' Robin'}, {name: 'Markus'},]; return ({users.map (user = > {user.name})});} export default App
Soon, every React developer gets used to JavaScript's built-in map () method. It is useful to map the array and return the rendered output of each item. In some cases, it is more useful to use filter () or reduce () in combination, rather than just rendering the output for each item that is map.
Import React, {Component} from 'react'; class App extends Component {render () {var users = [{name:' Robin', isDeveloper: true}, {name: 'Markus', isDeveloper: false},] Return ({users .filter (user = > user.isDeveloper) .map (user = > {user.name})});}} export default App
In general, React developers are accustomed to using these built-in functions of JavaScript instead of using React-specific API. It's just the JavaScript in HTML.
Var, let and const in React
For newcomers to React, using var, let, and const to declare variables may also be confusing, although they are not React-related. I will try to introduce let and const as early as possible in teaching, starting with the alternate use of const and var in React components:
Import React, {Component} from 'react'; class App extends Component {render () {const users = [{name:' Robin'}, {name: 'Markus'},]; return ({users.map (user = > {user.name})});} export default App
Then I give some rules of thumb for using these variable declarations:
(1) do not use var because let and const are more specific
(2) const is used by default because it cannot be reassigned or reassigned
(3) use let if you want to reassign variables
Let is commonly used in for loops, and const is usually used to keep the JavaScript variable unchanged. Although you can modify the internal properties of objects and arrays when using const, variable declarations express the intention to keep variables unchanged.
Ternary operators in React
What if I want to do conditional rendering through the if-else statement? We cannot use the if-else statement directly in JSX, but we can return it early from the rendering function. If you don't need to display content, returning null is legal in React.
Import React, {Component} from 'react'; class App extends Component {render () {const users = [{name:' Robin'}, {name: 'Markus'},]; const showUsers = false; if (! showUsers) {return null;} return ({users.map (user = > {user.name})}) }} export default App
However, if you want to use the if-else statement in the returned JSX, you can use the ternary operator of JavaScript:
Import React, {Component} from 'react'; class App extends Component {render () {const users = [{name:' Robin'}, {name: 'Markus'},]; const showUsers = false Return ({showUsers? ({users.map (user = > {user.name})}): (null)});} export default App
If you return only one aspect of conditional rendering, you can use the & & operator:
Import React, {Component} from 'react'; class App extends Component {render () {const users = [{name:' Robin'}, {name: 'Markus'},]; const showUsers = false Return ({showUsers & & ({users.map (user = > {user.name});} export default App
I won't go into the details, but if you are interested, you can learn more about this article (https://www.robinwieruch.de/conditional-rendering-react/) and other techniques related to conditional rendering. Conditional rendering in React tells us that most React is related to JavaScript, not React-specific content.
Import and export statements in React
In JavaScript, we can import and export functions defined in the JavaScript ES6 file through import and export statements.
These import and export statements are another topic to know before you start your React application. The create-react-app project is already using the import statement:
Import React, {Component} from 'react'; import logo from'. / logo.svg'; import'. / App.css'; class App extends Component {render () {return (
Welcome to React To get started, edit src/App.js and save to reload.
);} export default App
This is great for the initial project because it gives you a comprehensive experience of importing and exporting other files. However, when I first came into contact with React, I tried to avoid these imports. Instead, I will focus on JSX and React components. Import and export statements are introduced only when you need to separate React components or JavaScript functions into separate files.
What about using these import and export statements like this? Suppose you want to export the following variables of a file:
Const firstname = 'Robin'; const lastname =' Wieruch'; export {firstname, lastname}
You can then import * * files into another file through their relative paths:
Import {firstname, lastname} from'. / file1.js'; console.log (firstname); / / output: Robin
So it's not necessarily just about importing or exporting components or functions, it can be sharing everything that can be assigned to variables (let's just talk about JS). You can also import all variables exported from another file as an object:
Import * as person from'. / file1.js'; console.log (person.firstname); / / output: Robin
Imports can have aliases. Aliases are required when importing functionality with the same export name from multiple files.
Import {firstname as username} from'. / file1.js'; console.log (username); / / output: Robin
All the previous examples are named imports and exports. In addition, there are default imports and exports. It can be used in some of the following scenarios:
Export and import individual features
Emphasize the main functions of a module exporting API
As a backup for the import function.
Const robin = {firstname: 'Robin', lastname:' Wieruch',}; export default robin
You can omit curly braces when using the default import:
Import developer from'. / file1.js'; console.log (developer); / / output: {firstname: 'Robin', lastname:' Wieruch'}
In addition, the import name can be different from the default name of the export. You can also use it with named export and import statements:
Const firstname = 'Robin'; const lastname =' Wieruch'; const person = {firstname, lastname,}; export {firstname, lastname,}; export default person
Import in another file:
Import developer, {firstname, lastname} from'. / file1.js'; console.log (developer); / / output: {firstname: 'Robin', lastname:' Wieruch'} console.log (firstname, lastname); / / output: Robin Wieruch
You can also save some lines and export named variables directly:
Export const firstname = 'Robin'; export const lastname =' Wieruch'
These are the main functions of the ES6 module. They can help you better organize your code and design a reusable module API.
Libraries in React
React is just the view layer of the application. React provides some internal state management, but beyond that, it is just a component library that renders HTML for browsers. API (such as browsers API, DOM API), JavaScript, or external libraries can add something extra to React. Choosing the right library for your React application is not easy, but once you have a good understanding of the different libraries, you can choose the library that works best for your technology stack.
For example, we can use React's native API to get data:
Import React, {Component} from 'react'; class App extends Component {state = {data: null,}; componentDidMount () {fetch (' https://api.mydomain.com'). Then (response = > response.json ()). Then (data = > this.setState ({data}));} render () {.} export default App
But you can also use another library to get data, and Axios is one such popular library:
Import React, {Component} from 'react'; import axios from' axios'; class App extends Component {state = {data: null,}; componentDidMount () {axios.get ('https://api.mydomain.com'). Then (data = > this.setState ({data}));} render () {.} export default App
Therefore, once you know what problems need to be solved, React's ecosystem can provide you with a large number of solutions. This may not be about React itself, but about understanding how to choose the various JavaScript libraries that can be used to complement React applications.
Higher order functions in React
High-order functions are a great concept in functional programming. In React, it makes sense to understand these functions, because at some point you need to deal with higher-order components, and if you already know higher-order functions, you can better understand these high-order components.
Let's assume that the user list can be filtered based on the value of an input field.
Import React, {Component} from 'react'; class App extends Component {state = {query:',}; onChange = event = > {this.setState ({query: event.target.value});} render () {const users = [{name: 'Robin'}, {name:' Markus'},] Return ({users .filter (user = > this.state.query = user.name) .map (user = > {user.name})});}} export default App
We don't always want to do this by extracting functions, because it adds unnecessary complexity. However, by extracting the function, we can test it separately. So let's use the built-in filter function to implement this example.
Import React, {Component} from 'react'; function doFilter (user) {return query = user.name;} class App extends Component {... Render () {const users = [{name: 'Robin'}, {name:' Markus'},]; return ({users .filter (doFilter) .map (user = > {user.name})}) }} export default App
This implementation doesn't work yet, because the doFilter () function needs to know the query property of state. We can pass it through another wrapper function, that is, a higher-order function.
Import React, {Component} from 'react'; function doFilter (query) {return function (user) {return query = user.name;}} class App extends Component {... Render () {const users = [{name: 'Robin'}, {name:' Markus'},]; return ({users .filter (doFilter (this.state.query)) .map (user = > {user.name})}) }} export default App
Basically, higher-order functions are functions that can return functions. By using JavaScript ES6's arrow function, you can make higher-order functions more concise. In addition, this simplified approach makes it more attractive to combine functions into functions.
Const doFilter = query = > user = > query = = user.name
You can now export the doFilter () function from a file and test it separately as a pure (high-order) function. After understanding the higher-order functions, it lays the foundation for learning the high-order components of React.
Extracting these functions into (high-order) functions outside of React components also helps to test the local state management of React separately.
Export const doIncrement = state = > ({counter: state.counter + 1}); export const doDecrement = state = > ({counter: state.counter-1}); class Counter extends Component {state = {counter: 0,}; onIncrement = () = > {this.setState (doIncrement);} onDecrement = () = > {this.setState (doDecrement);} render () {return ()
{this.state.counter}
Increment Decrement);}}
Functional programming is very powerful, and turning to functional programming helps to understand the benefits of JavaScript treating functions as first-class citizens.
Deconstruction and expansion operators in React
Another language feature introduced in JavaScript is called deconstruction. Typically, you need to access a large number of properties in the state or props of the component. You can use deconstruction assignments in JavaScript instead of assigning them to variables one by one.
/ / no destructuring const users = this.state.users; const counter = this.state.counter; / / destructuring const {users, counter} = this.state
This is particularly useful for functional stateless components because they can receive props objects in the function signature. Usually, what you use is not props, but the content in props, so you can deconstruct what is already in the function signature.
/ / no destructuring function Greeting (props) {return {props.greeting};} / destructuring function Greeting ({greeting}) {return {greeting};}
Deconstruction also applies to JavaScript arrays. Another great feature is residual deconstruction. It is typically used to split some of the properties of an object and leave the remaining attributes in another object.
/ / rest destructuring const {users,... rest} = this.state
Uesrs can be rendered in the React component, while the rest of the state can be used elsewhere. This is where the JavaScript expansion (spread) operation works, which moves the rest of the object to the next component.
More JavaScript than React
React provides only a small surface area of API, so developers must get used to all the functionality provided by JavaScript. It's not without reason: "being a React developer will also make you a better JavaScript developer." Let's review some of the aspects of JavaScript we've learned by refactoring a high-level component.
Function withLoading (Component) {return class WithLoading extends {render () {const {isLoading,... props} = this.props; if (isLoading) {return
Loading
;} return;}}
This high-level component is used to display the conditional loading progress bar. When isLoading is set to true, the loading progress bar can be displayed, otherwise the input component will be rendered. Here you can see the practical application of the (remaining) deconstruction and expansion operator. The latter can be seen in the rendered Component because the remaining properties of the props object are passed to that Component.
The * step to make high-level components more concise is to reconstruct the returned React-class components into functional stateless components:
Function withLoading (Component) {return function ({isLoading,... props}) {if (isLoading) {return
Loading
;} return;}
As you can see, the remaining deconstruction can also be used in the signature of the function. Next, use the JavaScript ES6 arrow function to make higher-order components more concise:
Const withLoading = Component = > ({isLoading,... props}) = > {if (isLoading) {return
Loading
;} return;}
The function body can be shortened to one line of code by using the ternary operator. So you can omit the function body and the return statement.
Const withLoading = Component = > ({isLoading,... props}) = > isLoading?
Loading
:
As you can see, higher-order components use a variety of JavaScript-related techniques rather than React-related technologies: arrow functions, higher-order functions, ternary operators, deconstruction and expansion operators.
"how to learn JavaScript" content is introduced here, thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.