Before learning React you need to know the basics of JavaScript

During my workshops, more material about the JavaScript rather than React. Most attributed JavaScript ES6 and functionality and syntax, but also including ternary operator abbreviated version, language, object, JavaScript function built concept (map, reduce, filter) or common sense, such as: a combination of resistance, reusability, invariance or higher-order functions. These are the basics before you start using React You do not need to master the basics, but it would appear the basics when learning or practice it.

The following exercise is what I try to provide you with a concise but almost extensive list, which lists all the different JavaScript functions to complement your React application. If you have any other content not in the list, just to comment on this article, I'll update.

table of Contents

React to learn from JavaScript

When you enter the world React, usually use for starting React project the Create-REACT-App . After setting the items, you will encounter the following React class components:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      <div>
        <header>
          <img src alt="logo" />
          <h1>Welcome to React</h1>
        </header>
        <p>
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default App;

It can be said, React class components may not be the best starting point. Novice there are many things to digest, not necessarily React: class statement, class methods, and inheritance. Import statements only when learning React adds complexity. Although the main focus should be JSX (grammar React), but usually need to explain everything. This article should reveal everything, most of JavaScript, without fear of React.

React and JavaScript classes

React class components encountered in the beginning, but need JavaScript basis of the relevant class. JavaScript class is fairly new in the language. Previously, only JavaScript prototype chain can also be used to inherit. JavaScript classes on inheritance to build a prototype, so that the whole thing easier.

A method is defined React component class using JavaScript. To understand JavaScript class, you can spend some time studying them without React situation.

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());

It describes a class entity that serves as a blueprint for creating the entity instance. By using newstatement creates an instance of the class, it will call the class constructor, the instance of the class is instantiated. Thus, generally you may have a class constructor in its properties. In addition, a class method (e.g. getName ()) data (or writing) Examples for reading. Examples of this object class is represented in the class, but only to a specified instance of an external JavaScript variable.

Typically, a class inheritance in object-oriented programming. They used the same in JavaScript, and extends statement can be used a class inherits from another class. More professional class with the extends statement inherits all the features of more general classes, but you can add it to their specific functions.

class Developer {
  constructor(firstname, lastname) {
    this.firstname = firstname;
    this.lastname = lastname;
  }

  getName() {
    return this.firstname + ' ' + this.lastname;
  }
}

class ReactDeveloper extends Developer {
  getJob() {
    return 'React Developer';
  }
}

var me = new ReactDeveloper('Robin', 'Wieruch');

console.log(me.getName());
console.log(me.getJob());

Basically, it only requires a thorough understanding React class components. JavaScript class is used to define React component, but as you can see, is only one component React React component because it inherits all the features React React Component classes from package import.

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <div>
        <h1>Welcome to React</h1>
      </div>
    );
  }
}

export default App;

This is why the render () method is required in React class components: React React components imported from the package instructs you to use it to display some content in the browser. In addition, if you do not expand from React component, you will not be able to use other life-cycle approach (including the render () method). For example, componentDidMount () method does not exist life cycle, because the component is an instance of class vanilla JavaScript. And not only the life-cycle approach will disappear, React API methods (for example this.setState local state management ()) are not available.

But, as you can see, the use of JavaScript class is conducive to extend the use of your professional conduct generic class. Therefore, you can introduce your own class method or property.

import React, { Component } from 'react';

class App extends Component {
  getGreeting() {
    return 'Welcome to React';
  }

  render() {
    return (
      <div>
        <h1>{this.getGreeting()}</h1>
      </div>
    );
  }
}

export default App;

Now you know why React use JavaScript classes to define React class components. React when you need to access the API (life-cycle approach, this.state and this.setState ()), you can use them. In the following, you will see how different ways defined React assembly, without the use of JavaScript classes, because you may not always use the class methods, life-cycle approach and state.

After all, JavaScript classes are welcome to use the inheritance React, React This is not an ideal result, because React prefer a combination rather than inheritance . Therefore, you should be the only type your React component extension should be the official React components.

React arrow function

When teaching about React, I have long explained the JavaScript arrow Functions . It is one of ES6 grammar, it promotes the development of JavaScript in 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';

JavaScript function arrow React commonly used in applications to maintain simplicity and readable codes. I try to reconstruct functions from JavaScript ES5 to ES6 function. At some point, when the difference between the JavaScript ES5 function and JavaScript ES6 function Obviously, I stick with JavaScript ES6 way to achieve an arrow function. But I always see too many different React novice syntax may make people know what to do. So I try to use them all before use in React, the characteristics of the different JavaScript functions become clear. In the following section, you will learn how to function in a common JavaScript arrow in React.

As the assembly function React

React to use a different programming paradigm, because JavaScript is a multifaceted programming language. When the object-oriented programming, React component class using JavaScript class this way (React component API inheritance, class methods and class attributes, such as this.state). On the other hand, React (and ecosystem) the concept of using a lot of functional programming. For example, a stateless React functional component is another method of assembly defined in React. In React on stateless components led to a new way of thinking: how to use components like a function?

function (props) {
  return view;
}

It is a receiving input (e.g., props) and returned to the display of HTML elements (view) of the function (function). It does not need to manage any state (stateless), you do not need to know any of the methods (class methods, life-cycle approach). This function only need to use React component render () method of rendering mechanism. It was time to introduce non-state components.

function Greeting(props) {
  return <h1>{props.greeting}</h1>;
}

Stateless components is the preferred method of assembly is defined in React. They have less model, reduced complexity, and easier to maintain than React class components. But, for now, both have their own meaning of existence.

Previously, the article mentions arrow JavaScript function and how they can improve your React code. Let these functions be applied to your stateless components.
Greeting the group to look at using different ES5 and ES6 writing:

// JavaScript ES5 function
function Greeting(props) {
  return <h1>{props.greeting}</h1>;
}

// JavaScript ES6 arrow function
const Greeting = (props) => {
  return <h1>{props.greeting}</h1>;
}

// JavaScript ES6 arrow function without body and implicit return
const Greeting = (props) =>
  <h1>{props.greeting}</h1>

Arrow JavaScript function is stateless components simple way to keep in good React in. When there is no more calculation time can be omitted and the function thereof a return statement.

React grammar class components

React way to define the components evolve over time. In the early stages, React.createClass () method is to create a default React class components. Today, it is no longer used, because with the rise of JavaScript ES6, ES6 more is to use to create React class components.

However, the continuous development of JavaScript, so JavaScript enthusiasts are always looking for new ways of doing things. This is why you will often find different syntax React class components. A method of using the state and class class method definitions React following components:

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 (
      <div>
        <p>{this.state.counter}</p>

        <button onClick={this.onIncrement} type="button">Increment</button>
        <button onClick={this.onDecrement} type="button">Decrement</button>
      </div>
    );
  }
}

However, when implementing a large number of component class React, constructor binding class method and having a first constructor becomes cumbersome implementation details. Fortunately, there is a brief syntax to get rid of these troubles:

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 (
      <div>
        <p>{this.state.counter}</p>

        <button onClick={this.onIncrement} type="button">Increment</button>
        <button onClick={this.onDecrement} type="button">Decrement</button>
      </div>
    );
  }
}

By using the arrow JavaScript function, you can automatically bind the class methods, without binding them in the constructor. By directly is defined as a state class attribute may be omitted when not in use props constructor. (Note: Please note that the class attribute has not been used JavaScript language.) Therefore, you can say that the way this definition React class components are more compact than other versions.

The template text React

Template text is another JavaScript language specific features JavaScript ES6 incidental. It is worth mentioning that, because when newcomers and JavaScript React to see them, they will make people confused. The following is the syntax of the connection string you are using:

function getGreeting(what) {
  return 'Welcome to ' + what;
}

const greeting = getGreeting('JavaScript');
console.log(greeting);
// Welcome to JavaScript

Template text can be used the same text text, called string interpolation:

function getGreeting(what) {
  return Welcome to ${what};
}

You simply use ` ` and $ {} notation to insert JavaScript primitives. However, not only for the string literal string interpolation, JavaScript is also used in multi-line string:

function getGreeting(what) {
  return 
    Welcome
    to
    ${what}
  ;
}

Basically, this is how to format the text block is greater on multiple lines. Recently introduced GraphQL JavaScript can also be seen in it .

React in the Map, Reduce and Filter

What is the best way to React novice professor JSX grammar is? I generally define a first variable render () method, and which will block the return JavaScript as HTML.

import React, { Component } from 'react';

class App extends Component {
  render() {
    var greeting = 'Welcome to React';
    return (
      <div>
        <h1>{greeting}</h1>
      </div>
    );
  }
}

export default App;

You only need to use braces to get JavaScript HTML format. From string to render complex objects is no different.

import React, { Component } from 'react';

class App extends Component {
  render() {
    var user = { name: 'Robin' };
    return (
      <div>
        <h1>{user.name}</h1>
      </div>
    );
  }
}

export default App;

The next question usually is: how to present a list of items? In my opinion, this is one part of the explanation React best. React is not specific to the API, such as custom attributes on HTML tags, so you can render multiple items in React. You can use pure JavaScript to iterate through the list of items and return the HTML of each project.

import React, { Component } from 'react';

class App extends Component {
  render() {
    var users = [
      { name: 'Robin' },
      { name: 'Markus' },
    ];

    return (
      <ul>
        {users.map(function (user) {
          return <li>{user.name}</li>;
        })}
      </ul>
    );
  }
}

export default App;

Before using the arrow through the JavaScript function, you can get rid of the arrow and function body a return statement, so your rendering output is more concise.

import React, { Component } from 'react';

class App extends Component {
  render() {
    var users = [
      { name: 'Robin' },
      { name: 'Markus' },
    ];

    return (
      <ul>
        {users.map(user => <li>{user.name}</li>)}
      </ul>
    );
  }
}

export default App;

Soon, every React developers are accustomed to an array of built-in JavaScript map () method. Mapping array and returns each item rendered output is very meaningful. The same applies to the case of custom, which filter () or reduce () makes more sense, rather than showing output for each map entry.

import React, { Component } from 'react';

class App extends Component {
  render() {
    var users = [
      { name: 'Robin', isDeveloper: true },
      { name: 'Markus', isDeveloper: false },
    ];

    return (
      <ul>
        {users
          .filter(user => user.isDeveloper)
          .map(user => <li>{user.name}</li>)
        }
      </ul>
    );
  }
}

export default App;

Typically, this is how React developers accustomed to these built-in JavaScript functions without having to use React specific API. It is only in HTML JavaScript.

React in the var, let const and

Using the var, const, and let different variable declarations for the novice React it can be confusing, even though they are not React specific. Perhaps because of the introduction of JavaScript ES6 When React become popular. In general, I try in my studio and let const introduced as soon as possible. React it is only from the exchange assembly const var start with:

import React, { Component } from 'react';

class App extends Component {
  render() {
    const users = [
      { name: 'Robin' },
      { name: 'Markus' },
    ];

    return (
      <ul>
        {users.map(user => <li>{user.name}</li>)}
      </ul>
    );
  }
}

export default App;

Then I give a rule of thumb which use variable declarations:

  • (1) Do not use var, const, and more specifically, because let
  • (2) The default is const, because it can not be reassigned or re-statement
  • When using a let (3) re-assignment variables

Although let commonly used for loop to increment the iterator, but is commonly used to keep JavaScript const variables constant. Although you can change the internal properties of objects and arrays in the use of const, but variable declaration shows the intention of keeping variables constant.

React the ternary operator

If you are using the render if-else statement in JSX may be used JavaScripts ternary operator to do this:

import React, { Component } from 'react';

class App extends Component {
  render() {
    const users = [
      { name: 'Robin' },
      { name: 'Markus' },
    ];

    const showUsers = false;

    if (!showUsers) {
      return null;
    }

    return (
      <ul>
        {users.map(user => <li>{user.name}</li>)}
      </ul>
    );
  }
}

export default App;
import React, { Component } from 'react';

class App extends Component {
  render() {
    const users = [
      { name: 'Robin' },
      { name: 'Markus' },
    ];

    const showUsers = false;

    return (
      <div>
        {
          showUsers ? (
            <ul>
              {users.map(user => <li>{user.name}</li>)}
            </ul>
          ) : (
            null
          )
        }
      </div>
    );
  }
}

export default App;

Another way is, if you only return to conditions rendering side, use the && operator:

import React, { Component } from 'react';

class App extends Component {
  render() {
    const users = [
      { name: 'Robin' },
      { name: 'Markus' },
    ];

    const showUsers = false;

    return (
      <div>
        {
          showUsers && (
            <ul>
              {users.map(user => <li>{user.name}</li>)}
            </ul>
          )
        }
      </div>
    );
  }
}

export default App;

I will not explain in detail why this is so, but if you're curious, you can learn more about it and other technical conditions rendering: all conditions React in rendering . After all, React the conditions presented only display again most React React is JavaScript instead of any specific content.

React Import and Export of statements

Fortunately, JavaScript communities to identify the use of JavaScript ES6 the import and Export .

However, React and JavaScript ES6, the import and export of these statements just another theme needs to be explained at the beginning of the first React use application. We have long had the first import CSS, SVG, or other JavaScript files. create-react-app project has started from those import statements:

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      <div>
        <header>
          <img src alt="logo" />
          <h1>Welcome to React</h1>
        </header>
        <p>
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default App;

This is great because it provides for beginner projects you a full experience, you can import and export other files. App assembly also introduced in _src / index.js_ file. However, React in the implementation of the first step, I will try to avoid these imported at the beginning. Instead, I try to focus on the JSX and React components. Only when the first React component to another file or separate JavaScript function will be the introduction of import and export statements.

So these statements how to import and export work? Suppose you want to export the following variables in a file:

const firstname = 'Robin';
const lastname = 'Wieruch';

export { firstname, lastname };

Then, you can use a relative path of a file to import them to another file:

import { firstname, lastname } from './file1.js';

console.log(firstname);
// output: Robin

Thus, it is not necessarily about importing / exporting functions or components, but about everything can be assigned to shared variables (not CSS or SVG import / export, but talk about JS). You can also export all the variables in another file as an object import:

import * as person from './file1.js';

console.log(person.firstname);
// output: Robin

importing can have an alias. You may import function from multiple files with the same name exported. This is why you can use an alias:

import { firstname as username } from './file1.js';

console.log(username);
// output: Robin

All cases have been previously named as imports and exports. But there is a default statement. It can be used for some use cases:

  • Export and import functions of the individual
  • Export API function to highlight the main module
  • With back up import feature
const robin = {
  firstname: 'Robin',
  lastname: 'Wieruch',
};

export default robin;

You can omit the braces import to import the default export:

import developer from './file1.js';

console.log(developer);
// output: { firstname: 'Robin', lastname: 'Wieruch' }

In addition, import names may be different from the default name for export. You can also use it with the name of the export and import statements:

const firstname = 'Robin';
const lastname = 'Wieruch';

const person = {
  firstname,
  lastname,
};

export {
  firstname,
  lastname,
};

export default person;

In another file and import or export the default name is derived:

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 extra line and directly named Export Export variables:

export const firstname = 'Robin';
export const lastname = 'Wieruch';

These are the main features ES6 module. They can help you organize code and maintain code and design reusable modules API. You can also export and import capabilities to test them.

React in the library

React only view the application layer. React provided some internal state management, but other than that, it's just a render HTML component library for your browser. All other content can be, JavaScript function, or add an external library from the API (such as browser API, DOM API). Select the appropriate library to supplement React application does not always easy, but once you have different options for a good overview , you can choose the most suitable for your technology stack libraries.

For example, the machine may be used fetch API to obtain data in the React:

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 use another library to get data React in. Axios is a popular choice React application:

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 understand the problem to be solved, React extensive and innovative eco-system should provide a large number of solutions for you . It's not about React, but to understand all the different JavaScript libraries can be used to supplement the application.

React in higher-order functions

Higher order functions is a good programming concepts, especially when turning functional programming. In React, learn these functions are totally makes sense, because at some point you have to deal with the high-order components, which can be best explained in the first understand the higher-order functions.

We can show higher-order functions in the early React, without introducing higher order components. For example, assume that the user can filter the list presented based on the value 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 (
      <div>
        <ul>
          {users
            .filter(user => this.state.query === user.name)
            .map(user => <li>{user.name}</li>)
          }
        </ul>

        <input
          type="text"
          onChange={this.onChange}
        />
      </div>
    );
  }
}

export default App;

I do not always want to extract function, because it can increase the complexity of unnecessary, but on the other hand, it can have a beneficial effect for the learning JavaScript. In addition, by extracting function, you can isolate it with React components to be tested . So let's use the function to provide built-in filter function to show it.

import React, { Component } from 'react';

function doFilter(user) {
  return this.state.query === user.name;
}

class App extends Component {
  ...

  render() {
    const users = [
      { name: 'Robin' },
      { name: 'Markus' },
    ];

    return (
      <div>
        <ul>
          {users
            .filter(doFilter)
            .map(user => <li>{user.name}</li>)
          }
        </ul>

        <input
          type="text"
          onChange={this.onChange}
        />
      </div>
    );
  }
}

export default App;

Achieve before does not work because doFilter () function needs to know the query property from the state. Therefore, you can include it in another function leading to higher order function to pass it to the function.

import React, { Component } from 'react';

function doFilter(query) {
  return function (user) {
    return this.state.query === user.name;
  }
}

class App extends Component {
  ...

  render() {
    const users = [
      { name: 'Robin' },
      { name: 'Markus' },
    ];

    return (
      <div>
        <ul>
          {users
            .filter(doFilter(this.state.query))
            .map(user => <li>{user.name}</li>)
          }
        </ul>

        <input
          type="text"
          onChange={this.onChange}
        />
      </div>
    );
  }
}

export default App;

Basically, the higher-order function is a function that returns a function. By using JavaScript ES6 arrow function, you can make a higher order function more concise. In addition, this shorthand version will feature a combination of success can make more attractive.

const doFilter = query => user =>
  this.state.query === user.name;

You can now export doFilter () function from the file, and tested as a pure (high-order) function separately. After learning of the higher-order functions, we established all the basics, to learn more about the high-order components of React .

These functions will be extracted to outside React components (higher-order) function may also facilitate separate testing of local state management React.

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 (
      <div>
        <p>{this.state.counter}</p>

        <button onClick={this.onIncrement} type="button">Increment</button>
        <button onClick={this.onDecrement} type="button">Decrement</button>
      </div>
    );
  }
}

Move functions around the code base is a good way to understand the benefits of using a function as a fist class citizens in JavaScript. When the code is moved to functional programming, it is very powerful.

React Destructural and propagation operators

Another language feature introduced in JavaScript called deconstruction . Under normal circumstances, you must access large amounts of property from your state or assembly of props. You can use destructuring assignment in JavaScript, rather than one by one to assign them to variables.

// no destructuring
const users = this.state.users;
const counter = this.state.counter;

// destructuring
const { users, counter } = this.state;

This component is particularly useful for non-functional state, because they always receives props objects in the function signature. Typically, you will not use props but the use of props, so you can deconstruct the existing contents of the function signature.

// no destructuring
function Greeting(props) {
  return <h1>{props.greeting}</h1>;
}

// destructuring
function Greeting({ greeting }) {
  return <h1>{greeting}</h1>;
}

Deconstruction is also applicable to a JavaScript array. Another great feature is the rest of deconstruction. It is typically used to split a portion of the object, but the remaining attributes retained in another object.

// rest destructuring
const { users, ...rest } = this.state;

Thereafter, the user may be used for rendering, for example, in React components, used elsewhere in the rest state. That JavaScript extensions operator for forwarding the rest of the objects to a position of the lower assembly. In the next section, you will see the operation of this operator.

JavaScript is more important than React

In short, there are a lot of JavaScript can be used in React. While React only one API surface area, but developers have to get all the functionality provided by JavaScript. This sentence is not without reason: "React to become a developer will make you a better JavaScript developer." Let's reconstruct a higher-order components to review some aspects of learning in the JavaScript React.

function withLoading(Component) {
  return class WithLoading extends {
    render() {
      const { isLoading, ...props } = this.props;

      if (isLoading) {
        return <p>Loading</p>;
      }

      return <Component { ...props } />;
    }
  }
  };
}

IsLoading prop When set to true, this condition for displaying only the high-order component loading indicator. Otherwise, it presents an input component. You can already see the (rest) deconstruction and dissemination of operators. The latter can be seen in the Component rendered, because all the remaining props object attributes are passed to the Component.

The higher-order components cleaner first step is to reconstruct returned React class components to function stateless components:

function withLoading(Component) {
  return function ({ isLoading, ...props }) {
    if (isLoading) {
      return <p>Loading</p>;
    }

    return <Component { ...props } />;
  };
}

You can see the rest of deconstruction can also be used in the signature function. Next, use the arrow JavaScript ES6 high-order components function more concise:

const withLoading = Component => ({ isLoading, ...props }) => {
  if (isLoading) {
    return <p>Loading</p>;
  }

  return <Component { ...props } />;
}

Ternary operator can add function body shortened to one line of code. Function bodies can be omitted, and may be omitted return statement.

const withLoading = Component => ({ isLoading, ...props }) =>
  isLoading
    ? <p>Loading</p>
    : <Component { ...props } />

As you can see, the use of a variety of high-order components, rather than JavaScript React related art: arrow functions, higher-order functions, ternary operator, deconstruction and extended operator. This is how to use the JavaScript functions React application.


People often say that learning React learning curve is very steep. However, only the place all JavaScript excluded React to stay in the equation. When other Web frameworks being implemented, React does not add any external abstraction layer on top. Instead, you must use JavaScript. Therefore, JavaScript hone your skills, you will become a great React developers.


Guess you like

Origin www.cnblogs.com/homehtml/p/11877272.html
Recommended