The React of notes

Introduction of the React

The characteristics of the React

1. Declarative coding 2. Componentized coding 3. High efficiency (excellent Diffing algorithm)Copy the code

React is efficient

2. DOM Diffing algorithm minimizes page redrawingCopy the code

Virtual DOM vs. real DOM

1.React provides apis to create a "special" generic JS objectconst VDOM = React.createElement('xx', {id: 'xx'}, 'xx');
2.The virtual DOM objects are eventually converted to the real DOM by React3.When coding, we basically only need to operate virtual DOM data related to React. React will be converted to real DOM changes to update the interfaceCopy the code

React JSX

JSX
1.Full name: JavaScript XML2.React. CreateElement (Component, props,... Children) method of grammar sugar3.Purpose: To simplify the creation of virtual DOM1). Writing:var ele = <h1>Hello JSX!</h1>
    2). Note that1: It is not a string, nor an HTML/XML tag3). Note that2The result is a JS object4.Any tag name: HTML tag or other tags5.Tag attribute Arbitrary: HTML tag attribute or other6.Basic grammar rules1If you encounter code that starts with <, parse it in the syntax of the tag: HTML tags with the same name are converted to HTML elements with the same name2If you encounter code that begins with {, parse with JS syntax: the JS expression in the tag must be included with {}7.The role of Babel. Js1Browsers cannot parse JSX code directly and need Babel to translate it into pure JS code to run2Whenever JSX is used, add type="text/babel", the statement needs Babel to handleCopy the code

Render the virtual DOM (element)

Syntax: reactdom.render (virtualDOM, containerDOM); 2. Function: Render virtual DOM elements to display in the real container DOM in the page 3. Parameter description: 1). Parameter 1: pure JS or JSX created virtual DOM object 2). Parameter 2: The actual DOM element object used to contain the DOM element (usually a div)Copy the code

The event processing

1). React uses custom (synthesized) events instead of using native DOM events (native for example: Onclick) ----- for better compatibility 2). Events in React are handled by event delegation (delegating to the component's outer most element) ----- for efficiency 2. Get the DOM element object where the event occurred via event.targetCopy the code

React is component-oriented programming

The basic process of rendering class component labels

React creates a component instance object. 2. Render () to get the virtual DOM and parse it into the real DOM. Inserts inside the specified page number elementCopy the code

The three core attributes of a component

state
State is the most important attribute of the component object, and the value is the object (which can contain multiple key-value combinations). Components are referred to as "state machines", and the corresponding page display is updated by updating the component's state (re-rendering the component) // Strong note 1. This is the component instance object in the render method of the component. Component custom method this is undefined, how to solve? 1). Force bind this: through the function object bind() 2). Arrow function 3. State data, cannot be modified or updated directlyCopy the code
props
/ / understand
1.Each component object has the props(short for properties) property2.All properties of component tags are stored in props/ / function
1.Changing data is passed from component to component through label properties2.Note: Do not modify the props data inside the component// Encoding operation
1.Internally reads a property valuethis.props.name
2.Type and necessity restrictions on attribute values in props1React V15. 5Deprecated at start) person.proptypes = {name: React.PropTypes.string.isRequired,
        age: React.PropTypes.number
    }
	2Second way (new) : use prop-types library to restrict (need to introduce prop-types library) person. propTypes = {name: PropTypes.string.isRequired,
        age: PropTypes.number
    }
3.Extended Attributes: Pass all attributes of the object through porps <Person {... person} />4.Default attribute value person.propTypes = {name: 'Sketchy'.age: 18
}
5.Constructor of a component classconstructor(props) {
    super(props);
}
Copy the code
refs
/ / understandA label within a component can define a REF attribute to identify itself/ / code
1.The string is ref <input ref="input1"/ > values:this.refs.inputVal.value

2.Ref <input ref={val= > thisInputVal = val} /> Values:this.inputVal.value

3.MyRef = react. createRef() <input ref={this.myref} /> Values:this.myRef.current.value

/ / attentionGet the DOM element object where the event occurred via event.target ----- Don't overuse refCopy the code

The declaration cycle of the component

understand

2. The React component contains a series of hook functions (lifecycle callback functions) that are called at specific moments. 3. When we define a component, we do certain things in certain lifecycle callbacksCopy the code

Life cycle (old)

// Declare three phases of the cycle (old)
1.Initialization phase: ----- first render triggered by reactdom.render ()1). constructor(2).componentWillMount()
	3). render(4).componentDidMount() 2. Update phase: from within the componentthis.setState() or parent component againrenderTrigger a 1).shouldComponentUpdate(2).componentWillUpdate()
	3). render(4).componentDidUpdate() 3. Uninstall components fromReactDOM.umountComponentAtNode() trigger 1).componentWillUnmount()
Copy the code

Life cycle (New)

// Three phases of the lifecycle (new)
1.Initialization phase: ----- first render triggered by reactdom.render ()1). constructor(2).getDerivedStateFromProps
    3). render(4).componentDidMount() 2. Update phase: from within the componentthis.setState() or parent component againrenderTrigger a 1).getDerivedStateFromProps
    2). shouldComponentUpdate()
	3). render(4).getSnapshotBeforeUpdate
    5). componentDidUpdate() 3. Uninstall components fromReactDOM.unmountComponentAtNode() the triggerCopy the code

Important Hooks

1.Render: Initialize render or update render call2.ComponentDidMount: Enables listening to send Ajax requests3.ComponentWillUnmount: Do some finishing touches, such as cleaning timersCopy the code

A hook that is about to be discarded

1. componentWillMount
2. componentWillReceiveProps
3.ComponentWillUpdate is now used with a warning, the next big version will need to add UNSAFE_ prefix to use, may be completely deprecated later, not recommendedCopy the code

React Application (Based on React scaffolding)

The react of scaffolding

1. Scaffolding: used to help programmers quickly create a template project based on XXX library 1). Contains all required configuration (syntax checking, JSX compilation, devServer...) React provides a scaffolding library for creating react projects: create-react-app 3. React + Webpack + ES6 + ESLint 4. The characteristics of projects developed using scaffolding: modular, componentized, engineeredCopy the code

Create the project and start it

NPM i-g create-react-app switch to the directory where you want to create the project, run the NPX create-react-app hello-react command. CD Hello-react Step 4: Start the project: NPM startCopy the code

React Scaffolding project structure

Public static resource folder - the favicon. Icon -- -- -- -- -- - site TAB icon index. HTML -- -- -- -- -- -- -- -- the main page logo192. PNG -- -- -- -- -- -- -- the logo figure logo512. PNG -- -- -- -- -- -- -- Logo figure manifest. Json -- -- -- -- -- the packer application configuration file robots. The TXT -- -- -- -- -- -- -- -- the crawler agreement file SRC -- source folder App. CSS -- -- -- -- -- -- -- -- the style of the App. The App component js -- -- -- -- -- -- -- -- -- App component app.test. js ---- Used to test the App index.css ------ style index.js ------- entry file logo.svg ------- Logo diagram ReportWebVitals.js -- Page performance analysis file (web-vitals library support) Setuptests.js ---- component unit test file (jest-DOM library support)Copy the code

React ajax

understand

Front that
React itself only focuses on the interface and does not contain the code to send ajax requests. 3. The React application needs to integrate a third-party Ajax library (or encapsulate it itself)Copy the code
Common Ajax request library
2. Axios: lightweight, recommended to use 1). Ajax encapsulating XMLHttpRequest objects 2).promise style 3). It can be used on the browser side and node server sideCopy the code

axios

A GET request
axios.get('/user? ID=12345')
  .then(function (response) {
    console.log(response.data);
  })
  .catch(function (error) {
    console.log(error);
  });

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
Copy the code
A POST request
axios.post('/user', {
  firstName: 'Fred'.lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Copy the code

Extension: Fetch

The characteristics of
1. Fetch: native function, no longer using XMLHttpRequest object to submit Ajax request 2. Older browsers may not support itCopy the code
A GET request
fetch(url).then(function(response) {
    return response.json()
  }).then(function(data) {
    console.log(data)
  }).catch(function(e) {
    console.log(e)
  });
Copy the code
A POST request
fetch(url, {
    method: "POST".body: JSON.stringify(data),
  }).then(function(data) {
    console.log(data)
  }).catch(function(e) {
    console.log(e)
  })
Copy the code

The React routing

The understanding of the SPA

1.Single Page Web Application (SPA)2.The entire application has only one complete page3.Clicking a link in a page does not refresh the page, only a partial update of the page4.The data needs to be retrieved via Ajax requests and presented asynchronously on the front endCopy the code

Understanding of routing

What is routing?
1.A route is a mapping (key: value)2.Key is the path, and value may befunctioncomponent
Copy the code
Classification of routing
1.Back-end routing:1A. value b. value C. value D. valuefunction, which is used to process requests submitted by clients.router.get(path, function(req, res)(3)nodeWhen receiving a request, find the matching route according to the request path, call the function in the route to process the request, and return the response data 2. Front-end routing: 1). Browser routing,valuecomponent2). Register route: <Route path= "/test" component={Test} />
    3). How it works: When the browser's path changes to /test, the current routing component becomes testCopy the code

The react – the router – the understanding of the dom

1. React plugin library 2. Implement SPA application 3. React based projects almost always use this libraryCopy the code

The react – the router – the dom API

Built-in component
1. 	<BrowserRouter>
2.	<HashRouter>
3.	<Route>
4.	<Redirect>
5.	<Link>
6.	<NavLink>
7.	<Switch>
Copy the code
other
1.The history object2.Match the object3.WithRouter functionCopy the code

Basic use of routing

To prepare
NPM install --save react-router-domCopy the code

State management

State management directory structure

Folder directory// Status management root directory
redux
	// Store various action objects
	actions			
    	test1.js	/ / object 1
		test1.js	2 / / object
	// It is used for initialization and processing
	reducers		
    	index.js	// This file is used to summarize all reducers into a total reducer
		test1.js	// Store information 1
		test2.js	// Store information 2
	// This module is used to define constant values of type type in action objects. The purpose is to make it easier to manage and prevent programmers from making mistakes
	constant.js		
	// The core managed object of the redux library
	store.js		
Copy the code

Store. Js configuration

/** This file is specifically used to expose a store object, the entire application has only one store object */

// createStore is introduced to create the core store object in Redux
import {createStore,applyMiddleware} from 'redux'
// Add the reducer after the summary
import reducer from './reducers'
// Redux-thunk is introduced to support asynchronous action
// Install: NPM I redux-thunk
import thunk from 'redux-thunk'
/ / introduce redux devtools -- the extension
NPM I redux-devtools-extension
import {composeWithDevTools} from 'redux-devtools-extension'

//暴露store 
export default createStore(reducer,composeWithDevTools(applyMiddleware(thunk)))
Copy the code

Constant. The js configuration

/* This module is used to define constant values of type type in action objects. The purpose of this module is to make it easier to manage and prevent programmers from miswriting words */
export const TEST1 = 'test1'
export const TEST2 = 'test2'
export const TEST3 = 'test3'
Copy the code

Js configuration for each object in action

/* This file specifically generates the action object */ for the Count component
import {INCREMENT,DECREMENT} from '.. /constant'

// Synchronous action is a generic Object whose action value is of type Object
export const increment = data= > ({type:INCREMENT,data})
export const decrement = data= > ({type:DECREMENT,data})

// An asynchronous action is an action whose value is a function. An asynchronous action usually calls a synchronous action.
export const incrementAsync = (data,time) = > {
	return (dispatch) = >{
		setTimeout(() = >{
			dispatch(increment(data))
		},time)
	}
}
Copy the code

Reducers files

Index. Js configuration
/* This file is used to summarize all the reducers into a total reducer */
// Introduce combineReducers, which is used to summarize multiple reducer
import {combineReducers} from 'redux'
// Import the reducer as the Count component service
import count from './count'
// Import the Reducer as the Person component service
import persons from './person'

// Summarize all the reducer into a total reducer
export default  combineReducers({
	count,
	persons
})
Copy the code
Other reducer configurations
The reducer function receives two parameters: preState and Action */. The reducer function receives two parameters: preState and Action */
import {INCREMENT,DECREMENT} from '.. /constant'

const initState = 0 // Initialization state
export default function countReducer(preState=initState,action){
	// console.log('countReducer@#@#@#');
	// Get type and data from the action object
	const {type,data} = action
	// How to process data according to type
	switch (type) {
		case INCREMENT: // Add
			return preState + data
		case DECREMENT: // If it is minus
			return preState - data
		default:
			returnpreState <! If you are working with objects, you can - {... preState, ... data} --> } }Copy the code

Use in REdux

import store from './redux/store';
import { userAction1 } from './redux/actions/user1';
import { userAction2 } from './redux/actions/user2';



// Get the data stored in redux
store.getState();
// Distribute the action, trigger the reducer call, and generate a new state
dispatch(action);		// Example: dispatch(userAction1)
// Register a listener to be called automatically when a new state is generated
subscribe(listener)		
// Example: store.subscribe(() => {Perform some operations such as:this.setState({})
})
Copy the code

Use in React-redux

// in app.js
// Can no longer be introduced in app.js for the purpose of wrapping
import store from './redux/store';
import { Provider } from 'react-redux';		
/ / and the parcel
<Provider store={store}>
    <div className="App">Some components...</div>
</Provider>

// In the component
import { connect } from 'react-redux';
// No longer exposes the export Default Class Home extends Component
/ / to
class Home extends Component {... Content}// If you are the one sending the action
export default connect(null, mapDispatchToProps)(Home);
// To receive a message
export default connect(mapStateToProps)(Home);

// Implementation of two functions - simple example
// The first function - after this. Props... You can see the data in
const mapStateToProps = (state) = > {
    return state;
}
// The second function - needs to call sendAction somewhere else,
const mapDispatchToProps = (dispatch) = > {
    return {
        sendAction: (You can take arguments like value) = > {
            dispatch({
                // The object is an action
                type: 'add_action'.data: 1 // Then replace value here})}}}Copy the code

redux

Redux understand

What is a redux?
Redux is a JS library for state management (not react). React works with React, Angular, vue, etc. Function: Centrally manages the state shared by multiple components in the React applicationCopy the code
When should REdux be used
1. The state of a component that requires other components to be readily available (shared) 2. One component needs to change the state (communication) of another component. 3. General principle: use it if you canCopy the code

The three core concepts of Redux

aciton
1.Object of action2.contains2Properties:1).type: identifies the attribute, the value is a string, unique, required attribute2).data: Data attribute, value type is arbitrary, optional attribute3.Example: {type: 'ADD_STUDENT'.data: {name: 'LueLueLue'.age: 20}}Copy the code
reducer
1. Used for initialization state and processing state 2. Generated pure function of new state according to old state and action during processingCopy the code
store
1. Objects that link State, Action and Reducer 2. How do I get this object? 1). import { createStore } from 'redux' 2). import reducer from './reducers' 3). const store = createStore(reducer) 3. What does this object do? 2). Dispatch (action) : distribute the action, trigger the reducer call, generate a new state 3). Subscribe (listener) : Register a listener, which is called automatically when a new state is generatedCopy the code

The core API of Redux

createStore()
Create a store object that contains the specified reducerCopy the code
Store object
1.Function: The core managed object of the Redux library2.It maintains internally:1). state
	2). reducer
3.Core usage:1). getState()
	2). dispatch(action)
	3). subscribe(listener)
4.Specific code:1). store.getState()
	2). store.dispatch({ type: 'INCREMENT', number })
	3). store.subscribe(render)
Copy the code

applyMiddleware()

What it does: Redux-based middleware (plug-in library) on applicationsCopy the code

combineReducers()

Function: Combine multiple Reducer functionsCopy the code

Redux asynchronous programming

understand
1. Redux cannot be handled asynchronously by default. 2.Copy the code
Using asynchronous middleware
npm install --save redux-thunk
Copy the code

react-redux

understand

Redux is designed to simplify the use of Redux in React applicationsCopy the code

React-redux divides all components into two broad categories

UI components
2. Receiving data (general data and functions) through props 3. Do not use any of Redux's APIS. 4. Generally save in the Components folderCopy the code
Container components
1. Manage data and business logic, not UI presentation 2. Use API of Redux 3. They are generally stored in containers foldersCopy the code

The relevant API

// Provider: Make state data available to all components
<Provider store={store}>
	<App/>
</Provider>

// connect: Used to wrap UI components to generate container components
import { connect } from 'react-redux';
connect(
	mapStateToprops,		
    mapDispatchToProps
)(Hello);

// mapStateToprops: Convert external data (that is, state objects) to tag properties of UI components
const mapStateToprops = function (state) {
  return {
    value: state
  }
} 

// mapDispatchToProps: Converts the function that distributes the action to the tag properties of the UI component
Copy the code

Use the Redux debugging tool

Install the Chrome plug-in
Redux DevTools
Copy the code
Download the tool dependency package
npm install --save-dev redux-devtools-extension
Copy the code

Pure functions and higher order functions

Pure functions

1. A special class of functions that take the same input (argument) and return the same output (return) 2. The following constraints must be observed: 1). Parameter data must not be overwritten; 2). No side effects, such as network requests, input and output devices; 3). Do not call impure methods such as date.now () or math.random (). 3. The Reducer function of redux must be a pure functionCopy the code

Higher-order functions

// Understand: a special class of functions
    1)1: Arguments are functions2)2: returns a function// Common higher-order functions:
    1Timer setting function2) array of forEach ()/map ()/filter ()/reduce/find/bind () () ()3)	promise
    4Connect function in react-redux// Function: can achieve more dynamic, more extensible functions
Copy the code