Water can put the stone through, ten thousand efforts to natural – zZ Sen
1.React scaffolding __create-react-app
Global erection scaffolding
$NPM install -g create-react-app // or $yarn add -g create-react-appCopy the code
Rapid construction of engineering projects based on scaffolding
$create-react-app XXX // XXX: The project name complies with the NPM package specification, using lowercase letters, digits, and dashesCopy the code
If YARN is installed on the PC, the installation is based on YARN by default
Install the latest version of scaffolding
The version number of NPM is required to be above 5.2, and it can be installed to the part in one step
$ npx create-react-app my-app
Copy the code
Scaffold Project Catalogue
- Node_modules: Installs all required modules.
- Public:Storing the compile template
- index.html:
Public resource files introduced in index.html, i.e. resources in public that are the same class as index.html, are prefixed with <%PUBLIC_URL%>(the current directory) at import time and will be processed when WebPack is compiled. The vue is BASE_URL < % % >
<head> ... <link rel="icon" href="`<%PUBLIC_URL%>/favicon.ico"/ >... </head> <body> // Put the last compiled HTML in a box with id root"root"></div> </body> Copy the code
- Public resources:Based on the
src
andlink
Call it into HTML, so Webpack doesn’t do anything about it.
Store some CommonJs/ES6Module specifications that are not supported. If you have to use them, import them here.
- src:Store project source code
- index.js:The current project entry is recommended
index.jsx
JSX file, webpack support. JSX file parsing and compilation, vscode can also recognize - API: Data processing API
- Store: REDUX public state management
- Assets: Stores public resources
- Routes: routes management
- Untis: Public JS module
- Components Common components
- index.js:The current project entry is recommended
- package.json:Default configuration list
- Production dependency
- React The React framework provides states, properties, components, and life cycles
- React-dom renders the JSX syntax into the actual DOM, which is displayed in the browser
- React-scripts contains the webPack configuration of the current engineering project. The scaffolding hides all webPack configuration items and dependencies in node_modules. React-scripts The react script will tell Webpack to pack and compile.
- Scripts Scripts that the current project can execute ($yarn XXX)
- $yarn start => Start the project in the development environment (default is to create a service based on webpack-dev-server, which is used to compile and render the development content at any time)
- $YARN Build => In the production environment, package the content and compile it into the build file directory (server deployment).
- $yarn eject => expose all webpack configuration items hidden in node_modules (so that you can change the webpack configuration twice depending on your project needs)
- Production dependency
Yarn eject(Expose configuration files for secondary configuration)
-
Babel-preth-react-app parses JSX syntax
-
scripts
- Start. Js = > implementation
$ yarn start
Entry file of - Build. Js = > implementation
$ yarn build
Entry file of
If executing YARN Start /build prompts fewer modules, we will install whoever is missing
@babel/plugin-transform-react-jsx
@babel/plugin-transform-react-jsx-source
@babel/plugin-transform-react-jsx-self
- Start. Js = > implementation
-
The config | – is webpack configuration items stored here
PACKAGE.JSON
Configure the port number, local domain name, and HTTPS
"scripts": {
"startMac": "PORT=8081 node scripts/start.js"."start": "set PORT=8081&&set HOST=127.0.0.1&&set HTTPS=true&&node scripts/start.js"."build": "node scripts/build.js"
},
Copy the code
Example Modify the processing configuration of less
-
Install less and less-loader $YARN add less less-loader
-
Configure the config/webpack. Config. Js
const cssRegex = /\.(css|less)$/;
{
test: cssRegex,
exclude: cssModuleRegex,
use: getStyleLoaders({
importLoaders: 1,
sourceMap: isEnvProduction && shouldUseSourceMap,
}, "less-loader"),
// Don't consider CSS imports dead code even if the // containing package claims to have no side effects. // Remove this when webpack adds a warning or an error for this. // See https://github.com/webpack/webpack/issues/6571 sideEffects: true, },Copy the code
2.JSXJavaScript XML(HTML)
Basic grammar
What JSX writes is the virtual DOM
-
Each component view can have only one root element node: if necessary, add an empty Fragment document tag <>
ReactDOM.render([JSX],[CONTAINER],[CALLBACK])
[CONTAINER]
It is not recommended to be body or HTML and specify an element container[CALLBACK]
Rendering the virtual DOM to the page and then triggering the callback is not usually used
-
JSX syntax uses braces to bind dynamic data values to JS expressions
null
andundefined
Represents the empty element- in
{}
Other reference data types (other than arrays) cannot be written to objects or functions in. Arrays are converted to strings. - JSX virtual DOM objects can be placed in
{}
-
Set the class name and style for JSX
- Set the style class name for the JSX element
className
- To style a JSX element, you must place an object,
- if
{}
The result can be the new JSX element or the element value
- Set the style class name for the JSX element
-
Dynamically binding data
- JSX syntax uses curly braces to bind data, and the curly braces must contain only empty elements and arrays. In addition, they must be JS expressions, so you can use curly braces to bind data in an array based on methods that return a value.
- In JSX syntax, loops bind data by adding one to each loop
key
Because thekey
Is an important credential in DOM DIFF,key
The value is typically not set to the index of the loop, but is set to a unique constant value
let name = "zZ",
styObj = {color:'blue'},
data=[
{
id:1,
name:'shu'
},
{
id:2,
name:'gang'}]; ReactDOM.render(<div className="box" style={styObj}>
<ul>
data.map(item=>{
return <li key={item.id}>
<span>{item.name}</span>
<span>{item.name}</span>
</li>
})
</ul>
</div>)
Copy the code
The index here cannot be indexed. The main purpose is to make the rendering faster and less prone to component errors when data changes and DIFF rendering.
3. Virtual DOM to real DOM
1. Change the JSX syntax to create-element format using the pabel-react-app syntax package
The template template is parsed using vue-loader in Vue
ReactDOM.render(<div className="box"Style ={styObj}> zZ is a good boy <span> </span> </div>)Copy the code
Parsed to the following format:
React.createElement("div",{
className:"box",
style:{color:"blue"}},"zZ\u662f\u4e2a\u597d\u7537\u5b69",React.creatElement("span",null,"\u4f18\u79c0"))
Copy the code
- Each tag is resolved to a create-Element format
- By parsing, you build a tree that builds from right to left and from bottom to top from the lowest child node at compile time
2. Perform the React. CreateElement method ()
What is returned is an object: it is a virtual DOM
? typeof
:Symbol(react.element),key
:null,ref
:null,type
: Label name/component nameprops
: Attributes assigned to the element label, except key and refchildren
: The children attribute is available if the element has child nodes, and the value depends on the type of child nodes.- In the case of a single child node, the attribute value is a string or object
- If there are multiple child nodes, the property value is array
3. Perform the REACT – DOM. RENDER
The render function converts the object returned by executing React. CreateElement () into a real DOM and renders it into the specified container for rendering on the page.
4. Realization principle of virtual DOM to real DOM
To simulate how the virtual DOM goes to the real DOM, encapsulate the following code:
letReact = {}, ReactDOM={}; // Manipulating private properties directly exposes the property name and value to the callback functionfunction each(obj,callback){
Obiect.keys(obj).forEach(item=>{
let val = obj[item];
callback && callback(val,item)
})
}
React.creatElement = function createElement(type,props,... children){let virtualDOM = {
type, props:{}, key:null, ref:null }; / / processing propsif(props){
each(props,(value,item)=>{
if(item === "key"){
virtualDOM.key = value;
return
}
if(item === "ref"){
virtualDOM.ref = value;
return
}
})
delete props["key"];
delete props["ref"]; virtualDOM.props = {... Props}} // Handle childrenif(children.length>0){ virtualDOM.props.children = children.length===1 ? Children [0] : children}} // Convert virtual DOM to real DOM reactdom.render =function render(virtualDOM,container,callback){
let {
type,
props
}=virtualDOM;
let element = document.createElement(type);
each(props,(val,item)=>{
if(item==="className"){
element.className = val;
return;
}
if(item==="style"){
each(item,(value,key)=>{
element.["style"] ["key"] = value;
})
return;
}
if(item === "children") {letchildren = val; Children = Array,isArray(children)? children : [children]; each(children,(val,item)=>{if(typeof val === "string"){
element.appendChild(document.creatTextNode(val));
return
}
render(val,element)
})
returnElement.setattribute (item,val)}) // Put it in the specified container. AppendChild (element);if(typeof callback === "function"){ callback(); }}export default {React,ReactDOM}
Copy the code
5. The component
Components in React: Each component (class component) is a separate entity (data is private, has full lifecycle functions, and has its own view)
Component names can end with the.jsx suffix, and in the create-React-app scaffold creation project, include the. JSX file processing
1. Component classification
- Function component (static component) : A function returns a JSX object. Make it dynamic via HOOKS
- Class component (dynamic component) : Creates a class and inherits it
React.Component/PureComponent
, and must have a render function to render the view, which returns JSX - REACT HOOKS
2. The difference between dynamic and static components
- Static components do not have their own state, lifecycle functions, etc., so components are fixed once rendered, but can be used multiple times. Advantages: fast rendering, easy development and maintenance. Cons: Static and simple
- Dynamic component: it has its own state and life cycle functions. Even after rendering, it can re-render the modified part by changing the state. It has the advantages of powerful functions and dynamic data management, but has the disadvantages of slow operation speed
- The most common one is
HOOKS
According to the needs of the business, the function static component is made dynamic to realize the state and life cycle of the dynamic component and modify DOM elements through refs.
3. Invoke components
In JSX syntax, when reactdom. render is used to process a component, when it finds that type is not a tag string, it executes the current component, if it is a function component, it executes directly, if it is a class component, it executes new, and creates an instance. And pass props passed in by the parent component calling the child component to the function or instance for rendering. Note two points: Unlike vUE, both single-closed and double-closed labels work. Props is read-only and cannot be modified
When a parent component calls a child component, it passes properties, tags, and other components to the child component via the props property, as opposed to a vue slot. When the React. CreateElement method forms the virtual DOM, it will be stored in the props property of the JSX object. The tags and components will be stored in the props property named Children. React provides a set of methods to traverse children => children. Children has five methods: ①count/②forEach③map④only ⑤toArray. Second: use the index to get each item in the children array and put it in a different location.
Class components
【 inheritance 】 : 1. Prototype inheritance 2. Call inheritance 3. Parasitic combined inheritance 4
[super] similar to call inheritance, the parent class is executed as a function, with this in the function being an instance of the subclass. Constructor must be present in the current class. And the properties passed in when the component is called are passed to constructor. In REACT, the class component inherits react.component. when super is executed, react.componentis treated as a normal function, with THIS being the current instance. this=>{props:xxx,content:xxx,refs:{},updater:{… }} In order for the properties passed in to mount to the instance, props is passed to super.
When react-dom.RENDER is performed, if TEPE in the virtual DOM is a class component, it creates an instance of the class and passes it to the functions that it resolves, so constructor can receive the props. Create an instance of the current class after executing constructor. Although props was passed to constructor, these properties are not mounted on the instance. The value cannot be obtained based on this.props, but the props in the parameter can be used directly. When constructor is done, REACT will help us continue processing, using the render method to render the PROPS/CONTEXT… Later lifecycle functions can get and apply the passed property values based on this.props. You must have the render function, which returns the view of the current component to render.
4.Component&PureComponent
React provides two classes: ① Component ② PureComponent. The difference between the two parent classes is: PureComponent, relative to Component, creates a hook function shouldComponentUpdate by default. If we add shouldComponentUpdate manually, we’ll use the one we added. ShouldComponentUpdate is a shallow comparison. It passes in new data and returns true or false based on the class.
Note that when changing the state of an array or other reference data type, note that the address is not updated and the stored value is changed, it is still not rendered. New addresses are given based on the deconstruction to the new array, and true is returned before the view is rendered.
import React from 'react';
export default class Vote extends React.PureComponent {
state = {
arr: [10, 20]
};
render() {
return <div className="voteBox">
{this.state.arr.map((item, index) => {
return<span key={index}> {item} </span>; } <button onClick={this.handle}> button </button> </div>; } handle = () => {let arr = this.state.arr;
arr.push(30);
this.setState({
arr: [...arr]
});
}
Copy the code
6. Data control
We call the state – or property-based updates that drive view rendering controlled components. Properties cannot be modified, but they can be modified by borrowing by setting default values, having the parent component re-call a state that passes a different property, or assigning a property value to the component. Uncontrolled components: Operate directly on the DOM without state control.
Attributes – props
Third party plugins [prop-types] are required to set rules for properties that do not block content rendering.
- Installation
$ npm install --save prop-types
//&
$yarn add prop-types
Copy the code
- Importing
import PropTypes from "prop-types";
//&
var PropTypes = require("prop-types");
Copy the code
- Set default: Without this property in props, the default value will be used
static defaultProps = {
title:ZZ was lazy ""
}
Copy the code
- How to configure other rules
PropTypes. IsRequired must pass PropTypes. String/bool/number/func/object/symbol/node (element node)
Element (JSX element)
InstanceOf (Xxx)(must be an instanceOf a class)
OneOf ([“News”,”photos”])(oneOf many)
OneOfType ([PropTypes PropTypes. String, number, PropTypes. InstanceOf (Message)]) is one of the multiple types
static propTypes = {
title"PropTypes.string.isRequired
}
Copy the code
State — State (private state/public state REDUX)
1. Initialize in the constructor constructor, which requires state to be initialized for later use in the component
2. The setState method is used to tell the view to re-render. SetState (partialState,callback), which is asynchronous in some cases, is also understood to be locally asynchronous in hook functions. It is necessary to wait for the periodic function to complete execution before modifying the state, which ensures the stability of the periodic function and the integrity of the whole execution logic. In some cases it is synchronous. When you set a timer or perform setState in a binding event, it is synchronous and goes through the process of changing the state.
-
Asynchronous case:
- In the hook function
componentWillMount
React to avoid unnecessary re-renderingcomponentWillMount
, immediately changes the status. Local asynchrony is implemented. - In the hook function
componentDidMount
SetState is set to render, so asynchronously wait until the life cycle function is executed before modifying the state.
- In the hook function
-
Synchronization:
- Set timer: add a layer of timer in the modification state, itself in the asynchronous operation, do not consider the timer internal will affect the component life cycle function execution order and logic. Just do it in the order you want to change the state.
- Bind events: When you bind a level 2 event to the DOM, it is also asynchronous, triggering an operation to perform the bound operation, so the change state at this time does not affect the normal lifecycle of the component function execution logic.
-
Procedure => shouldComponentUpdate -> WillUpdate -> render -> DidUpdate
-
React merges and replaces the original state with the passed partialState. The first parameter is the partialState object. Use native Object.assign(this.state,partialState)
-
Callback is executed after the view is rerendered. You can solve the asynchronous setState situation, in which an AXIOS request can be made in the callback if the view has modified the data and is fetching the latest data from the server, passing the modified parameters.
3. Update status in batches
React queues the current asynchronous state change task based on setState. If another task changes the same state, the last task takes precedence. It’s the same with the browser rendering update mechanism. To avoid unnecessary rendering and improve performance.
4. This.forceupdate (): forceUpdate, implement this method should not go shouldComponentUpdate, modify state directly
5. Comparison of data-driven mechanisms
- React: Manually add changes based on setState/forceUpate and notify render to rerender
- 【 vue 】 : based on the built-in Object. DefineProperty/Proxy notice to render exercised by the setter (version 3.0).
this.state = {
time: new Date().toLocaleString()
};
render() {return <div>
<p>{this.state.time}</p>
</div>
}
componentDidMount(){// The first time the component has been loaded and rendered is equivalent to MOUNT in VUE //this case does not inform the component to re-render //this.state.time ="0 minute 0 second, January 1, 1970."// Each change is based on:setState methodsetInterval(()=>{
this.setState({
time: new Date().toLocaleString();
},()=>{console.log("The outbreak will be over soon!")})
},1000);
}
Copy the code
6. Refs: is an object that stores the element DOM with the attribute ref to obtain the DOM for operation. (ref=xxXxx, this.refs.xxxxx) ② Through the mode of the function, the parameter passed is the current DOM element, and then the DOM element is directly mounted to the instance, and then the corresponding DOM element is obtained by setting the attribute name to operate the DOM.
<p ref="timeBox">{new Date().toLoacaleString}</p>
//&
<p ref=DOM=>{
this.timeBox = DOM
}>{new Date().toLoacaleString}</p>
Copy the code
-
React event binding
- Native DOM event binding:Based on the
refs
Or by mounting DOM elements directly to the instancecomponentDidMount
Bind events in a hook function - JSX ownComposite events:
onXxx
React All events are synthesized for compatibility and mobile event handling. Document delegates each type of event.
- Native DOM event binding:Based on the
7. Life cycle functions of class components
getDefaultProps
Gets the default value for the property and verifies the type of the passed propertyconstructor
getInitialState
In the implementationgetInitialState
Previously, if the current class component had a constructor, the constructor would be executed first to initialize state and mount information such as properties to the instancecomponentWillMount
This is where data can be retrieved from the server in advance of the first rendering and reassigned to the state or stored in redux.render
Rendering componentcomponentDidMount()
The first component rendering is complete, and then it is running. You are ready to get the DOM element.
【state 】
shouldComponentUpdate
The state change triggers the hook function, which can determine whether the update is necessary to avoid unnecessary updates, so as to optimize and returntrue
orfalse
To control whether to execute the next hook function, but no matter which one is returned, the state has changedcomponentWillUpdate
The previous hook function returnstrue
Execute, do a series of pre-update preparationsrender
Render again, rendering the part of the state changedcomponentDidUpdate
After the status update is complete, listen for property or state changes again.
【props 】
componentWillReceiveProps
Property changes trigger the hook function, which gets changes to a specific property, and then firesshouldComponentUpdate
To see if it can be updated.
“Discharge”
componentWillUnmount
Before a component is unloaded, the final finishing touches are done, and the entire lifecycle of the component is completed.
Code diagram and parameters of each periodic function
class Clock extends React.Component {
static defaultProps = {
time:"0 minute 0 second, January 1, 1970."
}
static propTypes = {
time:"instanceOf(Date)"
}
constructor(props){
super(props);
this.state = {t:0}
}
componentWillMount(){
console.log("Executive componentWillMount - -")}render(){
console.log("Executive render - -")
returnThe < div > < h2 > back to {this. State. The time} < / h2 > < button Onclick = {() = > {enclosing setState ({. T: this state. The t + 1})}} > {this. State. T} < / button > </div> }componentDidMount(){
console.log("Executive componentDidMount - -")
}
shouldComponentUpdate (nextProps,nextState) {
console.log("-- shouldComponentUpdate --",nextProps,nextState)
}
componentWillUpdate(){
console.log("Executive componentWillUpdate - -"} //rendercomponentDidUpdate(){
console.log("Executive componentDidUpdate - -")}componentWillUnmount(){
console.log("Executive componentWillUnmount - -")
}
}
React.render(<section>
<Clock></Clock>
</section>,document.getElementById("root"),_=>{alert("Ollie to.")})
Copy the code