preface

Summary: include these three months to encounter some feel good interview questions, three months did not write blog really some itching, ha ha ha. More than 7000 words, no respect

  • My front end of the road to advancement

  • Zhihu Column && Brief Book Feature: Front Aggressor (Zhihu) && Front Aggressor (Brief Book)

  • Blog address: Damonare’s personal blog

Fire is the test of gold, adversity of strong

The body of the

React versus Vue

Similarities:

  1. Data-driven views provide a responsive view component
  2. Both have Virtual DOM, componentized development, and the transfer of data between parent and child components through the props parameter. Both implement webComponents specification
  3. Unidirectional data flow
  4. Both support server-side rendering
  5. Both have solutions that support Native, ReactReact native, Vueweex

Difference:

  1. Community: React community is still much larger than Vue;

  2. Development mode: React is much more intrusive than Vue in view layer. React is strictly only for MVC view layer, while Vue is an implementation of MVVM mode.

  3. Data binding: Vue has implemented two-way data binding, React data flow is one-way

  4. Data rendering: React is faster than Vue for large data rendering because it takes more work to start up the rendering mechanism.

  5. Data updates: With dependency tracking, Vue defaults to optimisation: as much data as you move, it triggers updates, no more, no less. React has two choices in complex apps:

    (1). Manually add shouldComponentUpdate to avoid unwanted vDOM re-render. (2).Components use pureRenderMixin as much as possible, and then redux structure + Immutable.

  6. Development style preference: React recommends JSX + Inline style, which means “all in JS “. After Vue advanced recommendation is to use webpack + Vue-Loader single file component format, that is, HTML, CSS, JS written in the same file;

  7. Application scenarios: React with Redux architecture is suitable for complex projects with large scale multi-person collaboration; Vue is suitable for small fast projects. Vue is more flexible than React for projects that require a lot of customization of the DOM;

  8. Vue is better than React, which may be reflected in the fact that many people are not familiar with the JSX syntax and functional programming ideas of React, as well as the reasons why it is necessary to learn a series of ecology in order to maximize the power of React.

  9. Vue focuses on improving development efficiency, allowing front-end programmers to develop applications more quickly and conveniently. React focuses on changing development thinking, improving the depth and creativity of front-end programmers’ programming, and making front-end engineers real programmers rather than UI builders.

Gulp is different from Webpack

  1. Gulp is a tool that can be used to optimize front-end workflow such as automatically refreshing pages, combo, compressing CSS, JS, compiling less, etc. It is embodied as follows: Writing tasks in a gulp configuration file, Webpack is a packaging tool, or a modular solution. In fact, the first way that most people use WebPack is through the gulp-Webpack plug-in. Write a task to use WebPack to package some files on the front end;
  2. The tasks of gulp need to be written by yourself, while webpack has a ready-made solution, which only needs to be configured in webpack.config.js.

Prevent duplicate Ajax requests

  1. After the user clicks the button disabled;
  2. Function of the throttle
  3. Abort dropped the last request.

The event model

  • Capturing phase. Events propagate from document all the way down to the target element, checking in turn to see if any of the passing nodes are bound to the event listener function, and executing if so.
  • Event processing phase (target phase). The event reaches the target element, triggering the listener function of the target element.
  • The bubbling phase of events. Events bubble from the target element to document, checking to see if the passing node is bound to an event listener, and executing if so.

Browser caching mechanism

  1. Expires strategy

Expires is a Web server response header field that tells the browser in response to an HTTP request that data can be cached directly from the browser until the expiration date, without having to request it again. Expires is an HTTP 1.0 thing, and now the default browser uses HTTP 1.1 by default, so it’s largely ignored.

  1. The cache-control strategy

Cache-control works the same way as Expires in that it specifies the expiration date of the current resource and controls whether to Cache the data directly from the browser or resend the request to the server. However, cache-control has more options and Settings, and if set at the same time, it has a higher priority than Expires.

These are two ways to set the cache time. So what happens when the cache time runs out? Someone must have said, so ask again, that’s right. The question is what if the server resources are not updated? For example, if I have a cached jquery. js file, and the server does not update the jquery. js file when the cache time is up, we can use the local cached file directly. There’s no need to waste bandwidth and time requesting a new file! At this point we need to take a closer look at the HTTP parameters.

  1. Last-Modified/If-Modified-Since

Last-modified/if-modified-since should be used with cache-control.

  • Last-modified: Indicates the Last time the response resource was Modified. When the Web server responds to a request, it tells the browser when the resource was last modified (this parameter comes with cache-control).
  • If-modified-since: When a resource has expired (max-age with cache-control) and a last-Modified declaration is found, the web server is requested again with the above if-modified-since, indicating the request time. The Web server finds the header IF-modified-since upon receipt of the request and compares it to the last Modified time of the requested resource. If the last modification time is newer, it indicates that the resource has been modified again. The response message contains the entire resource content (written in the response message packet), which is HTTP 200. If the last modification time is old, it indicates that the resource has not been modified. The system responds to HTTP 304 (no package body is required to save browsing) and tells the browser to continue using the saved cache.
  1. ETag/If-None-Match

Etag/ if-none-match is also used with cache-control.

  • Etag: When the Web server responds to a request, it tells the browser the unique identifier of the current resource on the server (the generation rule is determined by the server).Apache, the value of ETag,The default is the index section (INode), Size (Size), and last modified time (MTime) of the file)HashAnd then we get.
  • If-none-match: When the resource expires (with the max-age identified by cache-control) and the resource is found to have the Etage declaration, the web server is requested again with the if-none-match (the value of Etag) above. After receiving the request, the Web server finds the if-none-match header, compares it with the corresponding verification string of the requested resource, and decides to return 200 or 304.
  1. The ETag and last-modified

Etags in HTTP1.1 are designed to solve several last-modified problems:

  • Last-modified is accurate only to the second level. If a file has been Modified more than once in less than a second, it will not be accurate
  • If some files are generated periodically, sometimes the contents don’t change at all, but last-modified does, rendering the file unusable
  • The server may not accurately obtain the file modification time, or the time is inconsistent with that of the proxy server

Etag is a unique identifier of the corresponding resource on the server that is generated automatically by the server or by the developer, which can control the cache more accurately. Last-modified and ETag can be used together. The server validates ETag** first. If the last-modified ** is consistent, the server will continue to compare the last-modified ** before deciding whether to return 304.

Ajax status values versus HTTP status codes

  • Status values for Ajax

0: (uninitialized) the open() method has not been called; 1: (load) the open() method has been called, the request is being sent, the send() method has not been called; 2: (loading complete) Send () has been called, the response header and the response status have been returned; 3: (interactive) response body download; The responseText already gets some data; 4: (Completed) The response content has been parsed and can be invoked by the user.

  • The HTTP status code

    200&OK: Request succeeded;

    204 & No Content: Request processed successfully, but No resources to return;

    206 & Partial Content: requests for a part of the resource (such as requests that load only the rest of the image);

    301&move Permanently: Permanently redirect;

    302 & Found: Temporary redirection;

    303 & See Other: The requested resource has another URI and should be requested using the GET method.

    304 & Not Modified: The server determines that the local cache is Not updated and can use the local cache directly.

    307 & Temporary Redirect;

    400&Bad Request: The Request packet has a syntax error.

    401 & Unauthorized: Requests require HTTP authentication.

    403 & Forbidden: The requested resource is rejected by the server, the access permission problem;

    404 & Not Found: No requested resource was Found on the server;

    500 & Internal Server Error: An Error occurred while the Server was executing the request;

    502 & Bad Gateway: Incorrect Gateway;

    503 & Service Unavailable: The server is overloaded or under maintenance and cannot process requests.

    504 & Gateway timeout: Gateway timeout;

The React principle of the router

1.History

  • History of older browsers: mainly implemented by hashing, corresponding tocreateHashHistory
  • Advanced browser: through HTML5 in the history, correspondingcreateBrowserHistory
  • In the Node environment: The storage is mainly stored in memeorycreateMemoryHistory

Internal createHistory implementation:

// Internal abstract implementation
function createHistory(options={}) {... return { listenBefore,// An internal hook mechanism that can perform certain behaviors before the location changes, AOP implementation
    listen, // Triggers a callback when the location changes
    transitionTo, // Execute the change to location
    push, / / change the location
    replace,
    go,
    goBack,
    goForward,
    createKey, // Create a key for the location that uniquely identifies the location and is randomly generated
    createPath,
    createHref,
    createLocation, / / create a location}}Copy the code

CreateLocation method:

function createLocation() {
  return {
    pathname, // The base path of the URL
    search, // Query the field
    hash, // The hash value in the URL
    state, // State field corresponding to url
    action, // There are three types: push, replace and pop
    key Math.random().toString(36).substr(2, length)}}Copy the code

Each of the three methods performs URL progression:

  • createBrowserHistory: pushState, replaceState
  • createHashHistory: location.hash=*** location.replace()
  • createMemoryHistory: Stores historical records in memory

Pseudo code implementation:

// createBrowserHistory(HTML5) in the forward implementation
function finishTransition(location) {... const historyState = { key }; . if (location.action ==='PUSH')) {window.history.pushState(historyState, null, path);
  } else {
    window.history.replaceState(historyState, null, path)
  }
}
// Internal implementation of createHashHistory
function finishTransition(location) {... if (location.action ==='PUSH')) {window.location.hash = path;
  } else {
    window.location.replace(
    window.location.pathname + window.location.search + The '#'+ path ); }}// Internal implementation of createMemoryHistory
entries = [];
function finishTransition(location) {... switch (location.action) {case 'PUSH':
      entries.push(location);
      break;
    case 'REPLACE':
      entries[current] = location;
      break; }}Copy the code
  1. Basic principles of the React-Router

The URL corresponds to the Location object, and the UI is determined by the React components, thus turning into a synchronization issue between the Location and the components.

What is a prototype chain

Every object in the internal links to another object (the object prototype object), the object has a prototype prototype, when access to the object’s properties or methods, not only can find on the original object, will follow the prototype chain on the prototype object’s prototype chain lookup, up until the null (at the top of all the prototype chain). Prototypes are the basis of JavaScript implementation inheritance, and the main thing the new keyword does is point the __proto__ property of the instance object to the prototype of the object.

What is a closure

  • Closures are one way in which javascript supports first-class functions. They are expressions that refer to variables in their internal scope (the variables first declared in that scope). This expression can be assigned to a variable, passed to a function as an argument, or returned as a function return value.

  • A closure is a stack frame that is allocated at the start of a function’s execution and is not released when the function returns at the end of execution (just like a stack frame is allocated in the heap instead of the stack!).

  • Closure applications:

    • For example, when writing a curryization function, use closures to save the parameters in memory;
    var currying = function(fun) {
      	// Format arguments
    	var args = Array.prototype.slice.call(arguments.1);
      	return function() {
          	// Collect all parameters in the same array and calculate them
          	var _args = args.concat(Array.prototype.slice.call(arguments));
          	return fun.apply(null, _args);
      	};
    }
    Copy the code

    • Simulate private variables or private methods;
    const people = (num) = > {
      	var num = num;
      	return {
        	increase: (a)= > {
              	num++;
    		},
          	get: (a)= > {
              	returnnum; }}}const man = people(4);
    man.increase();
    man.get();
    Copy the code
    • Avoid references
    for (var i = 0; i < 4; i++) {
      	(function(_i) {
          	setTimeout(function() {
          		console.log(_i)
    		}, 1000)
      	})(i)
    }
    Copy the code

Image lazy loading and preloading

  • The principle of lazy image loading is to temporarily not set the SRC attribute of the image, but to hide the URL of the image, for example, first write in the data-src, and when some events trigger (such as scrolling to the bottom, click to load the image) then put the real URL of the image into the SRC attribute, so as to achieve the image lazy loading

  • Image preloading, refers to the need to show a large number of images in some websites, to achieve the image of the early loading. This improves the user experience. There are two commonly used ways, one is hidden in the BACKGROUND URL property of CSS, the other is through javascript Image object set instance object SRC property to achieve the Image preloading. The relevant code is as follows:

    1. CSS preloading images:
    #preload-01 { background: url(http://domain.tld/image-01.png) no-repeat -9999px -9999px; }  
    #preload-02 { background: url(http://domain.tld/image-02.png) no-repeat -9999px -9999px; }  
    #preload-03 { background: url(http://domain.tld/image-03.png) no-repeat -9999px -9999px; }
    Copy the code
    1. Javascript preloads images:
    function preloadImg(url) {
        var img = new Image();
        img.src = url;
        if(img.complete) {
            // The next step is to use the image
            //do something here
        } else {
            img.onload = function() {
                // The next step is to use the image
                //do something here}; }}Copy the code

Cross domain

There are many ways to cross domains. The most common one is that jSONP mainly uses the open script strategy: the script tag introduces a js or another suffix (such as PHP, JSP, etc.) file that returns a call to a JS function. The downside is that only GET requests are supported and there are security issues.

CORS cross-domain, the key lies in the server, if the server implements the CORS cross-domain interface, then you can use Ajax (request path for the absolute path) for cross-domain requests. CORS requests are divided into two types, one is simple request, the other is non-simple request. A simple request is one where the request method is between HEAD,GET, and POST and the request header is limited to

  • Accept

  • Accept-Language

  • Content-Language

  • Content-type: Only three values: Application/X-www-form-urlencoded, Multipart /form-data, text/plain

Non-simple request request header:

(1) Access – Control – Request – Method

This field is required to list which HTTP methods are used for the browser’s CORS requests

(2) Access – Control – Request – Headers

This field is a comma-delimited string that specifies the additional header field that the browser CORS request will send

When performing a simple request, the browser adds the Origin field to the request header. The server uses this field to determine whether the requested domain name is within the permitted range and whether to return the Access-control-allow-Origin field. There are several types of response headers:

(1) Access – Control – Allow – Origin

This field is required. Its value is either the value of the Origin field at the time of the request, or an * to accept requests for any domain name.

(2) Access – Control – Allow – Credentials

This field is optional. Its value is a Boolean value indicating whether cookies are allowed to be sent. By default, cookies are not included in CORS requests. Set to true, indicating that the server explicitly permits the Cookie to be included in the request and sent to the server. This value can only be set to true. If the server does not want the browser to send cookies, remove this field.

(3) the Access – Control – Expose – Headers

This field is optional. When CORS requests, the XMLHttpRequest object’s getResponseHeader() method gets only six basic fields: Cache-control, content-language, Content-type, Expires, last-modified, and Pragma. If you want to get other fields, you must specify them in access-Control-exposure-headers.

(4)Access-Control-Max-Age

The access-control-max-age header field specifies the duration of the response to the precheck request.

(5)Access-Control-Allow-Methods

The access-control-allow-Methods header field is used to precheck the response to the request. This indicates which HTTP methods are allowed for the actual request.

(6)Access-Control-Allow-Headers

The access-control-allow-headers header field is used to precheck the response to a request. This specifies the header field allowed in the actual request.

Other methods: document.domin, HTML5 postMessage,window.name, etc

Function throttling and function stabilization

Function throttling allows functions to be regularly called, application scenarios: window-resize, game bullets fired (1s can only fire one bullet);

Function stabilization allows a function to take effect after a period of time after “call”. Application scenarios: input boxes (example: 500ms after the user stops typing before processing user data).

// Function throttling
/* * @params {Function} fun * @params {delay} number */
const throttle = (fun, delay, ... rest) = > {
    let last = null;
    return (a)= > {
        const now = + new Date(a);if(now - last > delay) { fun(rest); last = now; }}}/ / instance
const throttleExample  = throttle((a)= > console.log(1), 1000);
/ / call
throttleExample();
throttleExample();
throttleExample();
// Function stabilization
const debouce = (fun, delay, ... rest) = > {
    let timer = null;
    return (a)= > {
        clearTimeout(timer);
        timer = setTimeout((a)= >{ fun(rest); }, delay); }}/ / instance
const debouceExample = debouce((a)= > console.log(1), 1000);
/ / call
debouceExample();
debouceExample();
debouceExample();
Copy the code

Quick sort

  1. You pick an element out of the sequence, called the pivot,
  2. Reorder the sequence so that all elements smaller than the base value are placed in front of the base value and all elements larger than the base value are placed behind it (the same number can go either way). After the partition ends, the benchmark is in the middle of the series. This is called the partition ** operation.
  3. Recursively sort any subsequence of elements less than or greater than the reference value in a recursive motion.

O(n^{2}) : O(\log n)

var quickSort = function(arr) {
    console.time('2. Quicksort time '); &emsp; &emsp;if (arr.length <= 1) { returnarr; } &emsp; &emsp;var pivot = arr.splice(0.1) [0]; &emsp; &emsp;varleft = []; &emsp; &emsp;varright = []; &emsp; &emsp;for (var i = 0; i < arr.length; i++){ &emsp; &emsp; &emsp; &emsp;if(arr[i] < pivot) { &emsp; &emsp; &emsp; &emsp; &emsp; &emsp; left.push(arr[i]); &emsp; &emsp; &emsp; &emsp; }else{ &emsp; &emsp; &emsp; &emsp; &emsp; &emsp; right.push(arr[i]); &emsp; &emsp; &emsp; &emsp; } &emsp; &emsp; }console.timeEnd('2. Quicksort time '); &emsp; &emsp;return quickSort(left).concat([pivot], quickSort(right));
};
var arr=[3.44.38.5.47.15.36.26.27.2.46.4.19.50.48];
console.log(quickSort(arr));/ / [2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 44, 46, 47, 48, 50]
Copy the code

Differences between AMD and CMD

AMD is a normalized output of the RequireJS module definition in the promotion process. CMD is the normalized output of the SeaJS module definition in the promotion process.

  1. For dependent modules, AMD executes ahead of time and CMD executes late. Starting with 2.0, however, RequireJS was also changed to allow delayed execution (depending on how you write it). CMD advocates as lazy as possible.
  2. CMD advocates dependency near, AMD advocates dependency front.
  3. While AMD’s API defaults to one for multiple uses, CMD’s API is strictly differentiated and promotes a single responsibility. For example, in AMD, require is divided into global require and local require, both called require. In CMD, there is no global require. Instead, seajs.use is provided to load and start the module system according to its completeness. In CMD, every API is pure and simple.

What causes JavaScript memory leaks and how to manually free memory

Prone to leak scenarios

  • XMLHttpRequest leak occurs in IE7-8, frees the method, sets the XMLHttpRequest instance object to Null;
  • The loop-binding leak of COM objects such as DOM&BOM occurs in IE6-8. The release method, the loop-reference is cut off, and the application of the object is set to Null.
  • The timer (technically not a leak, it is owned by the closure, which is normal). Useless variables in the closure can be released using the DELETE operator.

JavaScript garbage collection mechanism

  • Reference counting

This algorithm simplifies the definition of “is the object no longer needed” to “has the object been referenced by other objects”. If there is no reference to the object (zero reference), the object is collected by the garbage collection mechanism.

Restriction: Cannot handle circular references. In the following example, two objects are created and refer to each other, forming a loop. They do not leave the function scope after they are called, so they are useless and can be recycled. However, the reference counting algorithm takes into account that they all have at least one reference to each other, so they are not recycled.

  • Mark clear

When a variable enters the environment, for example, declaring a variable in a function, the variable is marked as “entering the environment.” Logically, the memory occupied by variables entering the environment can never be freed, because they are likely to be used as soon as the execution flow enters the appropriate environment. When a variable leaves the environment, it is marked “out of the environment.”

At runtime, the garbage collector marks all variables stored in memory (you can use any notation, of course). It then unflags variables in the environment and variables referenced by variables in the environment (closures). Variables tagged after that are considered to be ready to be deleted because they are no longer accessible to variables in the environment. Finally, the garbage collector completes the cleanup, destroying the tagged values and reclaiming the memory space they occupy.

Corylized function

The so-called curlization function simply means to change a function that takes multiple arguments to one that takes only one argument. The template and example of a Currie function are as follows:

var currying = function(fun) {
  	// Format arguments
	var args = Array.prototype.slice.call(arguments.1);
  	return function() {
      	// Collect all parameters in the same array and calculate them
      	var _args = args.concat(Array.prototype.slice.call(arguments));
      	return fun.apply(null, _args);
  	};
}
var add = currying(function() {
	var args = Array.prototype.slice.call(arguments);
  	return args.reduce(function(a, b) {
		return a + b;
    });
})
add(1.2.4)
/ * * a classic interview question * function parameter uncertain callback function variable number * write function: 15 * * add (1, 2, 3, 4, 5) = = add (1, 2) (3, 4) (5) = = 15 * /
function add() {
    // On the first execution, define an array to store all parameters
    var _args = [].slice.call(arguments);
    // Internally declare a function that uses the closure feature to store _args and collect all parameter values
    var adder = function () {
        var _adder = function() {
            [].push.apply(_args, [].slice.call(arguments));
            return _adder;
        };

        // Take advantage of the implicit conversion feature to implicitly convert when it is finally performed and calculate the final value returned
        _adder.toString = function () {
            return _args.reduce(function (a, b) {
                return a + b;
            });
        }

        return _adder;
    }
    return adder.apply(null, _args);
}
// Output results, parameters that can be freely combined
console.log(add(1.2.3.4.5));  / / 15
console.log(add(1.2.3.4) (5));  / / 15
console.log(add(1) (2) (3) (4) (5));  / / 15
Copy the code

Less Common Features

  • Variable (@color = # FFF)
  • Mix (a Mixin)
  • Built-in functions (color, string, type determination, math)
  • cycle
  • nested
  • operation
  • Import (@ import)

Common ES6 features

  • Variable definitions (let and const, mutable and immutable, const defines special cases of objects)
  • Deconstruction assignment
  • Template string
  • Array new API(example: array.from (),entries(),values(),keys())
  • Arrow function (REST argument, extension operator, :: bind this)
  • Set and Map data structures (Set instance member values uniquely store key values, Map instances store key-value pairs)
  • Promise objects (Evolution of front-end asynchronous solutions, Generator functions, async functions)
  • Class syntax sugar (super keyword)

How setState works in React

Topic:

import React from 'react'
class App extends React.Component {
  constructor() {
    super(a);this.state = {
      value: 0
    }
  }
  componentDidMount() {
    this.setState({value: this.state.value + 1});
    console.log(this.state.value);
    this.setState({value: this.state.value + 1});
    console.log(this.state.value);
    this.setState({value: this.state.value + 1});
    console.log(this.state.value);
	setTimeout((a)= > {
      this.setState({value: this.state.value + 1});
      console.log(this.state.value);
      this.setState({value: this.state.value + 1});
      console.log(this.state.value);
	}, 0)}}Copy the code

Answer: 0, 0, 0, 2, 3;

Analysis:

When the setState method is called React recalls the render method to rerender the component; SetState updates state via a queue. When the setState method is called, the state to be updated is placed in the queue. This queue effectively updates state in batches.

Source address :enqueueUpdate

function enqueueUpdate(component) {
  ensureInjected();
  // Check whether the update mode is in batch mode
  if(! batchingStrategy.isBatchingUpdates) {/ / the key! The following code snippet is the source code for this method
    batchingStrategy.batchedUpdates(enqueueUpdate, component);
    return;
  }
  // If you are in batch update mode, save this component in dirtyComponents
  dirtyComponents.push(component);
}
Copy the code

Source address: ReactDefaultBatchingStrategy

/ / batchingStrategy object
var ReactDefaultBatchingStrategy = {
  // Note that the default is false
  isBatchingUpdates: false.batchedUpdates: function(callback, a, b, c, d, e) {
    var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;
    ReactDefaultBatchingStrategy.isBatchingUpdates = true;
    if (alreadyBatchingUpdates) {
      callback(a, b, c, d, e);
    } else {
      // Key!! Understanding of transactions
      transaction.perform(callback, null, a, b, c, d, e); }}};Copy the code

Source address: Transaction

As shown in figure: The transaction wraps the method (anyMethod in the figure) in a wrapper and executes the method through the perform method. The initialize method in all the wrappers is executed before the perform method is executed. Then execute all the close methods;

var Transaction = require('./Transaction');
// We define it ourselves
var MyTransaction = function() {  
  //do something
};
Object.assign(MyTransaction.prototype, Transaction.Mixin, {
  	// You need to define a getTransactionWrappers object that gets all initialize and close methods that you want to encapsulate
  	getTransactionWrappers: function() {    
  		return [{      
          	initialize: function() {        
              console.log('before method perform');      
            },      
          	close: function() {        
              console.log('after method perform'); }}]; }; });// Instantiate a transaction
var transaction = new MyTransaction();
// The method to be called
var testMethod = function() {
  console.log('test');
}
transaction.perform(testMethod);
//before method perform
//test
//after method perform
Copy the code

The key thing to understand is that the whole process of rendering the component into the DOM is already in one big transaction, So when componentDidMount method invokes the setState ReactDefaultBatchingStrategy. IsBatchingUpdates = true; This code has already been executed, so the result of setState is not immediately effective, but is thrown into the dirtyComponent; So the value of this.state.value will still be 0, and the two setStates in setTimeout will not be called batchedUpdates (isBatchingUpdates is false by default). So the setState method takes effect immediately, as does the second setSState

Introduction to XSS and CSRF

XSS is a type of cross-site scripting attack, which is a type of code injection. By injecting code into a web page, the attacker can see that other users are affected (the content of the code is requested by an external server).

CSRF is a cross-site request forgery, posing as a user to initiate a request, and completing some actions against the user’s request (deleting posts, changing passwords, sending emails, Posting, etc.)

Examples of defense methods:

  1. Filter some keywords and special characters (<>,? ,script, etc.), or encodeURIComponent for user input;
  2. Do not store user names and passwords in cookies. Hash Cookie information using algorithms such as MD5. If necessary, you can bind IP addresses to cookies.

Afterword.