React study notes two: the principle of react

1. A preliminary understanding of the principle of react:

1) Description of setState()

2) JSX syntax conversion

3) Component update mechanism

4) Optimized component performance

5) Virtual DOM and diff algorithm

 

1. Description of setState()

Role: modify state, update UI

1) setState() updates data asynchronously

this.state = {
  a: 0
}

this.setState({
  a: this.state.a + 1
})

console.log(this.state.a)

2) Call setState() multiple times and merge them into one render to improve page rendering performance;

Although the following setState is called twice, but the second time cannot rely on the first result for processing, because it is an asynchronous update

this.state = {
  a: 0
}

this.setState({
  a: this.state.a + 1  // 0 + 1
})

this.setState({
  a: this.state.a + 1   // 0 + 1
})

console.log(this.state.a)}  // 0

render() {
  return (
    <p>fhdufhud</p>
  )
}

The following syntax is also updated asynchronously, but the latest state is obtained in the callback

this.state = {
  a: 0
}

this.setState((state, props) => {
  return {
    a: state.a + 1  // 0 + 1
  }
})

this.setState((state, props) => {
  // state是更新后的数据
  return {
    a: state.a + 1  // 1 + 1
  }
})

console.log(this.state.a)}  // 0

render() {
  return (
    <p>fhdufhud</p>
  )
}

3) The second parameter fn of setState

this.setState((state, props) => {}, () => {console.log('在状态更新之后,立即执行某个操作')})

 

2. JSX grammar conversion process

1) JSX is syntactic sugar for createElement

2) JSX syntax is compiled into createElement() method by plugin @babel/preset-react

3) React elements: objects that describe what you see on the DOM

 

 3. Component update mechanism

setState() has two functions: modify state and update UI

Process: The parent component is re-rendered, and the child components of the current component will also be re-rendered

4. Component performance optimization

1) Reduce state : only store data related to component rendering, data that does not need to be rendered is not placed in the state, because the data update in the state will trigger the render of the component

For variables that are common in multiple methods, but are not used for rendering, put them in this

2) Avoid unnecessary re-rendering

Component update mechanism: if the parent component is re-rendered, the child components of the current component will also be re-rendered

Problem: The sub-components will be updated without any changes

Solution: Use the hook function shouldComponentUpdate (nextProps, nextState)

Function: return true to indicate rendering, false without rendering

const { threadId } = require("worker_threads");

shouldComponentUpdate(nextProps, nextState) {
   //  更新值和当前值做比较
  return nextState.number !== threadId.state.number
}

3) Use pure components: React.pureComponent

Pure component React.PureComponent is similar to React.component

Difference : the shouldComponent hook is implemented internally, no manual comparison is required

Principle : The inside of the pure component compares the values ​​of the two props state before and after to decide whether to re-render the component

Note : The internal comparison of pure components is shallow compare

For reference types, only compare whether the addresses of the objects are the same: Note that if the property value in props or state is a reference type, you need to create new data, do not directly modify the original data

const { threadId } = require("worker_threads")

// 对于objetc,创建新数据
const newObj = {...this.state.obj, number: 2}
this.setState({
  obj: newObj
})

// 对于array:不要用push pop  unshift shift等直接修改原数组的方法
// 用返回新数组的方法:concat  slice map 等
this.setState({
  list: [...this.state.list, {新数据}]
})

 

5. Virtual DOM and diff algorithm

1) Update the view idea : re-render the view when the state changes

2) Ideal state : Partial update, only update changes

3) Virtual DOM is essentially a JS object

Implementation process

1) For the first rendering, React will create a virtual DOM object (tree) based on the initial state

2) Generate the real DOM based on the virtual DOM and render it to the page

3) When the data changes (setState()), re-create a new virtual DOM object (tree) based on the new data

4) Compare with the virtual DOM object obtained last time, use the diff algorithm to get the content that needs to be updated

5) Finally, React only updates (patch) the changed content to the DOM and re-renders it to the page

When the diff algorithm is triggered

1) After the component is rendered, a virtual DOM object is generated according to the state and JSX structure

2) The diff algorithm occurs after the render

 

The true value of virtual DOM

Virtual DOM frees React from the shackles of the browser environment

 

Two, routing basic learning

1) The role of React routing

2) Basic use of react-router-dom

3) The execution process of routing

4) Use programmatic navigation to jump route

5) Default route

6) Matching mode of React routing

 

1. The role of React routing

Front-end routing function: Allow users to navigate from one view to another

Front-end routing is a set of mapping rules, which is the correspondence between URL paths and components

Using React routing is to configure paths and components (pairing)

 

2. Basic use of react-router-dom

Basic use

1) Install the routing package: react-router-dom

npm i react-router-dom

2) Import the three core components of routing Router/Route/Link

import { BrowserRouter as Router, Route, Link } from 'react-router-dom'

3) Use the Router component to wrap the entire application

<Router>
  <div className="app"></div>
</Router>

4) Use the Link component as the navigation menu (route entry)

<Link to="/first">page one</Link>

5) Use the Route component to configure routing rules and components to be displayed (route export)

const First = () => (<p>page one content</p>)

<Router>
  <div className="app">
    <Link to="/first">page one</Link>
    <Route path="/first" component={First}></Route>
  </div>
</Router>

Common component description

1) Router component "wraps the entire application, a React application only needs to be used once

2) Two commonly used Routers: HashRouter and BrowserRouter

3) hashRouter: use the hash value of the URL to achieve

4) BrowserRouter (recommended to use this mode): use H5's history API implementation

5) Link component: used to specify the navigation connection (a tag): Link is compiled into a, in BrowserRouter, to is equivalent to location.pathname

6) Route component: specify the relevant information of the route display component, path routing rules, component: the displayed component

 

3. The execution process of routing

1) Click on the Link component (a label) to modify the url in the browser address bar

2) React routing monitors the change of the address bar url

3) React routing internally traverses all Route components, using routing rules (path) to compare with pathname

4) When the routing rule path can match the pathname in the address bar, the content of the Route component will be displayed

 

4. Programmatic navigation

Programmatic navigation: realize page jump through js code

this.props.history.push('/home')

History is provided by React routing and is used to obtain information about browser history

1) push(path): Jump to a page, path represents the jump path

2) go(n): forward or backward to a certain page, (-1 to go back to the previous page, 1 to go to the next page)

 

5. The default route

Default route: indicates the route that will be matched when entering the page

1) The default route path is:/

<Route path="/" component={Home}></Route>

 

6. Matching mode

1) Fuzzy matching mode

Problem: When the to attribute value of the Link component is "/login", the default route will also match

Reason: React routing is fuzzy matching mode by default

Fuzzy matching rules: as long as pathname starts with path, it will match successfully

import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
const Home = () => (<p>默认页面</p>)
const Login = () => (<p>登录页面</p>)

const App = () => {
  <Router>
    <div className="app">
      {/* 点击这里,会将Home  Login都渲染 */}
      <Link to="/login">登录页面</Link>
      {/* 默认路由 */}
      <Route path="/" component={Home}/>
      <Route path="/login" component={Login}></Route>
    </div>
  </Router>
}

2) Exact match

Definition: Add the exact attribute to the Route component and it will become an exact match

Exact match: the route will only be displayed when path and pathname match exactly

{/* 默认路由 精确匹配*/}
<Route exact path="/" component={Home}/>

Add the exact attribute to the default route

Summary of routing basics

1) React routing can effectively manage multiple views (components) to achieve SPA

2) The Router component wraps the entire application and is only used once

3) The Link component is the entrance and the Route component is the exit

4) Programmatic navigation through props.history

5) Default fuzzy matching, add exact to change exact matching

6) Everything in React routing is a component

 

 

 

 

Guess you like

Origin blog.csdn.net/tangxiujiang/article/details/114459864