Key points:
-
React is one-way data binding, one-way data flow
-
Vue is bidirectional data binding, single data flow
-
All components in React are functions
Create the React application
1. Scaffolding construction
Creat-react -app React creates the scaffolding for the project
NPX create-react-app my-react(custom project name) CD my-react NPM run startCopy the code
Success page:
2. The file
- Index.js: react entry file to import:
import React from 'react';
import ReactDOM from 'react-dom';
Copy the code
3. The name of the class
- The className needs to be className, and if there are two classnames, the latter will replace the former. “Unlike VUE, VUE automatically incorporates CSS styles.” However, you can manually merge them yourself
let cls = 'box' ... <div className={'aaa' + cls}></div> Copy the code
- In htmlFor React, click the label next to the checkbox and check the checkbox.
<input type="checkbox" ID =" AA "/> <label htmlFor=" AA "> Select </label> // htmlFor serves idCopy the code
4. Inline style
Native writing:
<h1 style="color:red"></h1>
Copy the code
React generates an error. The correct way to write it is to put an object inside a variable
- Conjunctions are written in small hump form
< h1 style = {{color: 'red', fontSize: '20 px'}} > < / h1 > / / or let sty = {color: 'red'} < h1 style = {sty} > < / h1 >Copy the code
5. Common objects cannot be directly used as react sons
For example, to view object contents, convert the string “json.stringify ()”
Ii. Core Concepts
1. Element rendering
Update UI: reactdom.render ()
2. Components & props
(1) Component concept
- Components are functions and can be divided into two classes:
-
Hooks: special for functional components “to solve the problem where functional components have no state and no hook functions”
Function App(){return <> <h1> </h1> </>}Copy the code
-
Class components
Class App extends React.Component {render() {return (<h1> class component </h1>)}}Copy the code
-
- Component names must start with a capital letter (when used).
<Welcome name="sara"/>
- Components can be split and extracted/composed
- The Props are read-only, and all React components must protect their Props from being changed as if they were pure functions.
(2) Parent-child component communication
Simple implementation of the parent component to the child component parameters, the child component display li list; The child modifies the parent data by calling methods passed in by the parent.
A) Class component approach
parent.jsx
import React, { Component } from 'react' import Child from './child' export default class Parent extends React.Component { state = { List: [{name: 'zhang' age: 13}, {name: "bill", the age: 13}, {name: 'Cathy' age: 13}, {name: 'six liu, age: Parent_Del (n) {let temp = [...this.state.list] temp.splice(n, 1) this.setState({list: Temp})} render() {let {list} = this.state return (<div> parent component <Child data={list} onDel={this.parent_del.bind (this)} /> </div> ) } }Copy the code
child.jsx
import React, { Component } from 'react' export default class Child extends React.Component { child_Del(n) { this.props.onDel(n) } Render () {let {data = []} = this. Props return (<div> subcomponent <ul> {data.map((item, index) => { return ( <li key={item.name}> name: {item.name} <br /> age: {item. Age} < br / > < button onClick = {this. Child_Del. Bind (this, the index)} > delete < / button > < / li >)})} < / ul > < / div >)}}Copy the code
B) Functional component approach
parent.jsx
Function the Parent () {let data = [{name: 'zhang' age: 13}, {name: "bill", the age: 13}, {name: 'Cathy' age: 13}, {name: 'Liu Liu ', age: 13 } ] const [list, setList] = useState(data) const parent_Del = (n) => { let temp = [...list] temp.splice(n, 1) setList(temp)} return (<div> Parent component <Child data={list} onDel={parent_Del} /> </div>)} export default ParentCopy the code
child.jsx
Function Child(props) {let {data = []} = props const child_Del = (n) => {props. OnDel (n)} return (<div> subcomponent <ul> { data.map((item, index) => { return ( <li key={item.name}> name: {item.name} <br /> age: {item. Age} < br / > < button onClick = {() = > {child_Del (index)}} > delete < / button > < / li >)})} < / ul > < / div >)} export default ChildCopy the code
C) slot
Slots in React, receive via children
For example, writing slot content to a parent component:
<Child data={list}> <p>Copy the code
Child component: Children receive display
Function Child(props) {let {data = [], children} = props return (<div> <h2> sub-component </h2> {children} </div>)}Copy the code
D) Custom structure
For example, if a user wants to customize the structure of a child component from the parent component, he can pass render.
The child component checks if render is present and uses the content passed in to render instead of the default content
The parent component:
<Child
data={list}
render={(item) => {
return <h1>姓名:{item.name};年龄:{item.age}</h1>
}}>
</Child>
Copy the code
Child components:
return ( <li key={item.name}> { render ? render(item) : <span> name: {item.name} <br /> age: {item. Age} < br / > < / span >} < Button type = "primary" onClick = {() = > {child_Del (index)}} > delete < / Button > < / li >)Copy the code
(3) Controlled components and uncontrolled components
In a controlled component, form data is managed by the React component. Another alternative is to use uncontrolled components, where the form data is handed over to DOM nodes for processing. The official recommendation is to use controlled components to process form data.
Controlled component: a component that is under its own control
<input
type="text"
value={name}
onChange={(e) => { this.onChange(e) }} />
Copy the code
Uncontrolled component: Not controlled by the current component
- use
React.createRef()
Definition,this.xxx.current,value
Get component values
class input extends React.Component { state = { name: } WWW = react.createref () componentDidMount() {this.www.current.value = this.state.name} render() {return () <div> <input type="text" ref={this.www} /> </div> ) } }Copy the code
3. State & Life Cycle
(1) props
Called properties, the data passed in by the parent component
(2) State
- State is similar to props, but State is private and fully controlled by the current component
- Called state, the data that is proprietary to the component itself
class App extends React.Component { constructor() { super(); // es6 inheritance must call the constructor this. State = {}; Render () {return (<h1> class component </h1>)}}Copy the code
Props (this. Props) = props (this. Props)
(3) Lifecycle & hook functions
Class components have hook functions; functional components have no hook functions
-
To mount:
When a component instance is created and inserted into the Dom, its lifecycle is called in the following order:
-
constructor()
-
Static getDerivedStateFromProps() : “New”
-
Is called before render, at initialization and after update.
-
Cannot coexist with componentWillMount. The same (componentWillMount/UNSAFE_componentWillMount mean just version different writing, are not recommended to use, is abolished. Equivalent to beforeMount in Vue)
-
-
render()
-
ComponentDidMount () : “Common”
The Mounted method is emitted after the component has been loaded (rendered into the DOM).
Ajax requests are typically placed in componentDidMount()
-
-
Update:
Updates are triggered when a component’s props or state changes. Component updates are called in the lifecycle order as follows:
-
Static getDerivedStateFromProps() “New”
Perform the call before render
-
ShouldComponentUpdate ()
-
This is a hook function for optimization. Check whether the output of the React component is affected by changes to the current state or props based on the return value of shouldComponentUpdate()
-
ShouldComponentUpdate () is called before rendering when props or state changes. The default return value is true
shouldComponentUpdate(nextProps, nextState) Copy the code
-
-
render()
-
GetSnapshotBeforeUpdate () “New” “Common”
-
componentDidUpdate()
- Equivalent to the updated in VUE
-
-
Unmount:
Triggered when a component is removed from the Dom.
componentWillUnmount()
“Common”
Method clears component content, such as timers, equivalent to beforeDestroy in Vue
-
Error handling
When an error is thrown in a rendering process, lifecycle, or child component’s constructor, the following methods are called:
-
static getDerivedStateFromError()
Called after a descendant component throws an error, it takes the thrown error as an argument and returns a value to update state
-
componentDidCatch()
Called after a descendant component throws an error
-
-
other
ForceUpdate () forces re-rendering.
(5) the setState ()
For class components
class BusinessInfo extends React.Component { state = { count: 100 } add(num) { this.setState({ count:this.state.count + num }) } minus(num) { this.setState({ count:this.state.count - Num})} render() {let {count} = this.state return (<div> <h1> {count}</h1> <Button onClick={() => { this.add(10) }}>+</Button> <Button onClick={() => { this.minus(5) }}>-</Button> </div> ) } }Copy the code
-
(1) Do not modify state directly, because the code does not re-render the component. Use the setState() provided inside React instead.
this.state.count = this.state.count + num
The count data has changed, but the view does not, because of the monomial data stream, the component is not re-rendered
This.setstate ({count:this.state.count + num},function(){console.log(' data update completed ')})Copy the code
- SetState takes the second argument and fires when the data update is complete
The constructor is the only place you can assign a value to this.state.
-
(2) Update of State is asynchronous in most cases
For performance reasons, React may combine multiple setState() calls into one. This. Props and this. State may update asynchronously, so you can’t rely entirely on them to update the next state
This. SetState ((state,props) => {counter:state.counter + props. Increment}) this.setState(function(state,props){ return { counter:state.counter + props.increment } })Copy the code
-
(3) Updates of State will be merged
By merge, I mean that if the setState() method is used to update the data, the properties in the original state will not be lost on display.
“Unlike functional components using useState, unupdated content will be lost. See the userState summary in the Hook below for details.”
(6) One-way data flow
Any state is always owned by a particular component, and any data or UI derived from that state can only affect components “below” them in the tree.
4. Event handling
-
React event names use small humps, not pure lowercase
-
Using JSX syntax, you pass in a function as an event handler instead of a string.
<button onClick={activateLsasers}> Activate Lasers </button>
Copy the code
-
To preventDefault behavior, explicitly use preventDefault
-
Pass parameters to the event handler
Class array, we need to ensure that this in the function is the current instance
Mode 1: Arrow function mode “Event objects must be explicitly passed”
<button onClick={(e) => this.deleterow (id, e)}> Delete Row </buttonCopy the code
Option 2: Bind “Event objects and more parameters will be passed implicitly”
<button onClick={this.deleterow. bind(this,id)}> Delete Row </buttonCopy the code
this
In javaScript, class methods do not bind this by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when called
Class Toggle extends React.Component {constructor(props){super(props) // To use 'this' in a callback, HandleClick = this.handleclick. bind(this) // * key *}}Copy the code
5. Conditional rendering
- The element variables
- The and operator &&
- Ternary operator
Prevents component rendering: “Conditional rendering based on property values in props”
6. Lists & Keys
-
Use the map() method to traverse the array of numbers, place the traversed data in a tag such as
- tag, insert the array of
- tags into the
-
element, and render it into the Dom
{
list.map(item => {
return <li key={item.name}> {item.name} </li>
})
}
Copy the code
Key: Assigns a definite identity to each element in the array
- A unique string, usually using an ID in the data
- If there is no unique identifier such as id, you can use index index (if it is static data, it will not cause list order change, otherwise it will cause bugs)
- React defaults to index as key if you don’t specify key.
- Location: A good rule of thumb is: In
map()
The element in the method requires a key attribute.
7. The form
(1) input
Export default class Input extends React.Component {state = {name: 'chiu'} onChange(e){console.log(e.target.value); this.setState({ name:e.target.value }) } render() { let { name } = this.state return ( <div> <p>{name}</p> <input Type ="text" value={name} onChange={(e) => {this.onchange (e)}}Copy the code
8. State improvement
Official explanation: When multiple components need to reflect the same change data, we recommend promoting the shared state to the nearest common parent.
That is, the private state of the current component, promoted to the unified management of the upper component (depending on the parent or grandparent component), is the idea.
Third, the hooks
Hooks can only be used for the top-level scope, not for writing{}
This block-level scope, otherwise an error is reported.
1. useState
(1) Basic use
Using useState, we mainly solve the problem of functional components having no state of their own and no hook function feature.
Normal writing allows the data to change, but the view is not updated. To update the view, use useState in hook
import React, { useState } from 'react'; function BusinessInfo1() { let [getCount, setCount] = useState({ count: 100, name: 'A'}) const add = (num) => {// count = count + num // getCount, count:getCount.count + num }) } const minus = (num) => { setCount({ ... GetCount, count: getcount.count -num})} return (<div> <h1>{getCount.name}) {getCount.count}</h1> <Button onClick={() => { add(10) }}>+</Button> <Button onClick={() => { minus(5) }}>-</Button> </div> ) }Copy the code
let [getCount, setCount] = useState({ count: 100, name: 'A' })
- The parameters received by useState are initial values
- One problem with using useState is that it gets results that are not merged by default, but replaced, so you need to manually fill in the other attributes
. getCount
(2) Asynchronous operation
For example, when adding a timer to the cumulative count, the output of the timer is still the original value, not the latest value, because each time is an independent scope.
Function UseState1() {let [count, setCount] = useState(100) console.log(' ${count} times'); const log = () => { setTimeout(() => { console.log('log:', count); }, 2000) } return ( <div> <h1>{count}</h1> <button onClick={() => { setCount(count + 1) }}>+</button> <button onClick={log}>log</button> </div> ) }Copy the code
How to get the latest value? New data can be saved.
Method 1: Native method “Create external scope”
Note: //*** is the change point
//*** function UseState1() {let [count, setCount] = useState(100) console.log(' ${count} times'); const log = () => { setTimeout(() => { console.log('log:', outCount); //*** }, 2000) } return ( <div> <h1>{count}</h1> <button onClick={() => { setCount(count + 1); outCount = count + 1 }}>+</button> //*** <button onClick={log}>log</button> </div> ) }Copy the code
React: useRef() creates an external scope
function UseState1() {
let [count, setCount] = useState(100)
const ref = useRef() //***
const log = () => {
setTimeout(() => {
console.log('log:', ref.current); //***
}, 2000)
}
return (
<div>
<h1>{count}</h1>
<button onClick={() => { setCount(count + 1); ref.current = count + 1 }}>+</button> //***
<button onClick={log}>log</button>
</div>
)
}
Copy the code
Method 3: Callback functions
Function UseState1() {let [count, setCount] = useState(100) console.log(' ${count} times'); const log = () => { setTimeout(() => { setCount((newVal) => { //*** console.log(newVal); return newVal + 10 }) }, 2000) } return ( <div> <h1>{count}</h1> <button onClick={() => { setCount(count + 1) }}>+</button> <button onClick={log}>log</button> </div> ) }Copy the code
2. useEffect
Class components have hook functions, functional components do not have hook functions, so useEffect is needed
useEffect(() => { console.log('componentDidMount + componentDidUpdate'); }, [])Copy the code
-
UseEffect Takes two parameters (componentDidMount + componentDidUpdate). UseEffect takes two parameters (componentDidMount + componentDidUpdate).
-
Adding an empty array to the second argument is equivalent to just executing componentDidMount. (Initial loading will be performed)
-
The array contains dependencies, and only triggers this hook when the dependency changes
-
UseEffect callback function
useEffect(() => { return () => { } },[]) Copy the code
-
When is the returned callback executed? The next time the useEffect argument is executed, the callback returned by the previous argument is executed
-
The callback function can be equivalent to the componentWillUnmount function.
-
3. The memo is from the memo.
-
The memo handled component is equivalent to an automatic shouldComponentUpdate for the class component
-
As long as the data passed in does not change, the corresponding component will not be re-rendered
Child = memo(Child) Copy the code
-
React.memo is similar to PureComponent
Differences between the two:
React.memo
Only judgeprops
Whether it changes, changes trigger updates,state
Whether changes are not processed;PureComponent
Will be handled.
4. React.PureComponent
-
Inherit from the React.PureComponent, which internally implements shouleComponentUpdate and only performs shallow comparisons (referencing datatype, comparing only the first layer, not detected internally).
ShouleComponentUpdate (nextProps, nextState) accepts two parameters
-
There is a problem with react.component. the render function of the child component is reexecuted after the parent component is updated if no processing is done. If a component doesn’t need to be updated, use the shouleComponentUpdate hook function to determine that
5. UseMemo “Processes data”
UseMemo is used in conjunction with the Memo and caches object addresses.
It recalculates values when a dependency changes, an optimization that helps avoid costly calculations every time you render.
let obj = useMemo(() => {
}, [count])
Copy the code
- Parameter 1: callback function
- Parameter 2: dependency “Dependency (count) changes, gives OBj a new address; no new address is assigned if it does not change”
- Obj: callback result
Memo and useMemos sample code
function Child(props) {
console.log('render');
return <h1>{props.data.count}</h1>
}
const Childs = React.memo(Child)
function useMemos() {
let [count, setCount] = useState(100)
let [age, setAge] = useState(10)
let obj = useMemo(() => {
return {
count: count
}
}, [count])
return (
<div>
<Childs data={obj} />
<button onClick={() => { setCount(count + 3) }}>count + </button>
<h2>{age}</h2>
<button onClick={() => { setAge(age + 1) }}>age + </button>
</div>
)
}
Copy the code
6. useCallback
React.memo, useMemo, and useCallback are a combination used for optimization.
UseCallback is used to cache function addresses
let f = () => {
setCount(count + 10)
}
f = useCallback(f, [])
return (
<div>
<Childs data={obj} onChangeCount={f} />
<button onClick={() => { setCount(count + 3) }} >count + </button>
<h2>{age}</h2>
<button onClick={() => { setAge(age + 1) }}>age + </button>
</div>
)
Copy the code
7. useReducer
UseReducer is an alternative to useState
Four, routing,
1. Install
Use it in a browser
npm install react-router-dom
Copy the code
2. Basic components
(1) Router Components
<BrowserRouter>
: Browser mode<HashRouter>
: hash pattern
When using a routing component, be sure to use it on the root component.
(2) Route Matchers Components
<Route>
<Switch>
In
, multiple
addresses can be wrapped, and the browser will compare the path addresses in turn. If there is a match, the browser will display it. If there is no match, the browser will return null.
<Switch>
<Redirect path='/' exact to='/introduce'></Redirect>
<Route path='/introduce' component={Introduce}></Route>
<Route path="/Users" component={UserInfo}></Route>
</Switch>
Copy the code
exact
The path of the current route matches precisely
(3) Navigation Components
-
: will be rendered as a tag
<Link to="/">Home</Link> Copy the code
-
<NavLink>
-
: Forces a page to use this label, such as login.
Introduction of depend on
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
Copy the code
3. Other attributes
Lazy lazy loading
import React, { lazy } from 'react'
const login = lazy(() => import('@/views/Login'))
Copy the code
Suspense
Lazy loading