In 2021, React Family Bucket, working hard to punch in...

In 2021, React Family Bucket, working hard to punch in...

1. Write a hello world on the page

<body> <!-- Prepare a container --> <div id="app"></div> <!-- Introduce the react core library --> <script type="text/javascript" src="../js/react.development.js"></script> <!-- Introduce react-dom to support react operation DOM --> <script type="text/javascript" src="../js/react-dom.development.js"></script> <!-- Introduce babel to convert jsx to js --> <script type="text/javascript" src="../js/babel.min.js"></script> <script type="text/babel">/*This time must be text/babel*/ //1. Create a virtual dom const VDOM = <h1>Helo World</h1>/*Be sure not to add quotation marks*/ //2. Mount on the page ReactDOM.render(VDOM, document.getElementById('app')) </script> </body> Copy code

2. two ways to create virtual dom

1. Use jsx to create a virtual don

<body> <!-- Prepare a container --> <div id="app"></div> <!-- Introduce the react core library --> <script type="text/javascript" src="../js/react.development.js"></script> <!-- Introduce react-dom to support react operation DOM --> <script type="text/javascript" src="../js/react-dom.development.js"></script> <!-- Introduce babel to convert jsx to js --> <script type="text/javascript" src="../js/babel.min.js"></script> <script type="text/babel">/*This time must be text/babel*/ //1. Create a virtual dom const VDOM = <h1 id="title">Helo World</h1>/*Be sure not to add quotation marks*/ //2. Mount on the page ReactDOM.render(VDOM, document.getElementById('app')) </script> </body> Copy code

2. Use js to create virtual dom

<body> <!-- Prepare a container --> <div id="app"></div> <!-- Introduce the react core library --> <script type="text/javascript" src="../../js/react.development.js"></script> <!-- Introduce react-dom to support react operation DOM --> <script type="text/javascript" src="../../js/react-dom.development.js"></script> <script> //1. Create a virtual dom //const VDOM = React.createElment(tag name, white attributes, tag body) const VDOM = React.createElement('h1', {id:'title'},'js creates virtual dom') //2. Mount on the page ReactDOM.render(VDOM, document.getElementById('app')) </script> </body> Copy code

3. What is virtual dom? ?

  • Essentially an object of type object
  • Virtual dom will eventually be converted into real dom by react

Three.jsx syntax rules

  • 1. Don't use quotation marks when defining virtual dom
  • 2. Use {} when mixing js expressions in tags
  • 3. The style class name should use className
  • 4. Inline style style={{key: value}} is the form to write, the outermost {} represents a js expression, the inner {} represents an object
  • 5. Need a root tag
  • 6. The label needs to be closed
  • 7. The first letter of the label
    • If it starts with a lowercase letter, it will be converted into an html tag in react. If there is no tag with the same name, an error will be reported
    • If it starts with a capital letter, react will render the component, if there is no component, it will report an error
<body> <!-- Prepare a container --> <div id="app"></div> <!-- Introduce the react core library --> <script type="text/javascript" src="../js/react.development.js"></script> <!-- Introduce react-dom to support react operation DOM --> <script type="text/javascript" src="../js/react-dom.development.js"></script> <!-- Introduce babel to convert jsx to js --> <script type="text/javascript" src="../js/babel.min.js"></script> <script type="text/babel">/*This time must be text/babel*/ const myId ='box' //1. Create a virtual dom const VDOM = (/*Be sure not to add quotation marks*/ <div id={myId} className="box"> <h1 style={{color:'red'}}>Helo World</h1> <input type="text"/> </div> ) //2. Mount on the page ReactDOM.render(VDOM, document.getElementById('app')) </script> </body> Copy code

Four. Case

  • Distinguish the difference between js statements and expressions
    • Expression: An expression will produce a value, which can be used in any way that needs to be worthwhile
      • 1.a
      • 2.a+b
      • 3.demo(1)
      • 4.arr.map()
      • 5.function test(){}
    • Code (statement):
      • if(){}
      • for(){}
<body> <!-- Prepare a container --> <div id="app"></div> <!-- Introduce the react core library --> <script type="text/javascript" src="../js/react.development.js"></script> <!-- Introduce react-dom to support react operation DOM --> <script type="text/javascript" src="../js/react-dom.development.js"></script> <!-- Introduce babel to convert jsx to js --> <script type="text/javascript" src="../js/babel.min.js"></script> <script type="text/babel">/*This time must be text/babel*/ const myId ='box' //Simulation data const data = ['Chinese film','Hong Kong film','Japanese film'] //1. Create a virtual dom const VDOM = ( <div> <h2>Movie list</h2> <ul> { data.map(item => { return <li key={item}>{item}</li> }) } </ul> </div> ) //2. Mount on the page ReactDOM.render(VDOM, document.getElementById('app')) </script> </body> Copy code

V. Understanding of modules and components, modularization and componentization

1. Module

  • Understanding: js programs that provide specific functions to the outside world are generally js files
  • Role: reuse js, simplify js writing, and improve js operation efficiency

2. Components

  • Understanding: a collection of resources (html, css, js), etc. used to achieve partial functional effects and resources
  • Role: take code, simplify code writing

3. Modular

  • Understanding: When the application is written by js modules, it is a modular application

4. Componentization

  • Understanding: When the application is written by components, it is a componentized application

Six. react define components

1. Matters needing attention:

  • The first letter of the component name must be capitalized
  • The label must be a closed label
  • The virtual dom label can only have one root label

2. Functional components

  • The function must have a return value
<body> <!-- Prepare a container --> <div id="app"></div> <!-- Introduce the react core library --> <script type="text/javascript" src="../js/react.development.js"></script> <!-- Introduce react-dom to support react operation DOM --> <script type="text/javascript" src="../js/react-dom.development.js"></script> <!-- Introduce babel to convert jsx to js --> <script type="text/javascript" src="../js/babel.min.js"></script> <script type="text/babel">/*This time must be text/babel*/ //1. Create a function component function MyComponent() { return <h1>I am a functional component, [applicable to simple components]</h1> } //2. Mount on the page ReactDOM.render(<MyComponent/>, document.getElementById('app')) </script> </body> Copy code

3. Class components

  • Must extend React.Component
  • The render function must be used
  • There must be a return value in the render function
  • The first letter of the class name must be capitalized
<body> <!-- Prepare a container --> <div id="app"></div> <!-- Introduce the react core library --> <script type="text/javascript" src="../js/react.development.js"></script> <!-- Introduce react-dom to support react operation DOM --> <script type="text/javascript" src="../js/react-dom.development.js"></script> <!-- Introduce babel to convert jsx to js --> <script type="text/javascript" src="../js/babel.min.js"></script> <script type="text/babel">/*This time must be text/babel*/ //1. Create a class component class MyComponent extends React.Component{ render() { return ( <h1>I am a class component, [applicable to complex components]</h1> ) } } //2. Mount on the page ReactDOM.render(<MyComponent/>, document.getElementById('app')) </script> </body> Copy code

Six. 3.attributes of component instances

1.state

  • 1. This in the render method of the component is the component instance object
  • 2. In the method of component customization, this is undefined, how to solve it?
    • a) Mandatory binding this: through the bind() of the function object
    • b) Arrow function
  • 3. Status data, cannot be modified or updated directly
    • Use setState
<body> <!-- Prepare a container --> <div id="app"></div> <!-- Introduce the react core library --> <script type="text/javascript" src="../js/react.development.js"></script> <!-- Introduce react-dom to support react operation DOM --> <script type="text/javascript" src="../js/react-dom.development.js"></script> <!-- Introduce babel to convert jsx to js --> <script type="text/javascript" src="../js/babel.min.js"></script> <script type="text/babel">/*This time must be text/babel*/ class Weather extends React.Component { //omitted //constructor(props) { //super(props) //} //Initialization state state = { isHot: false } render() { const {isHot} = this.state return ( <h1 onClick={this.handleBtn}>Today s weather is very {isHot?'hot':'cool'}</h1> ) } //Custom method - use the form of assignment statement + arrow function handleBtn = () => { const {isHot} = this.state this.setState({ isHot: !isHot }) } } ReactDOM.render(<Weather/>, document.getElementById('app')) </script> </body> Copy code

2.props

  • Precautions
    • 1.porps is a read-only attribute and cannot be modified
    • 2. Whether the constructor accepts props and whether it is passed to super depends on whether you want to access props through thisf in the constructor
    • 3. Functional components, you can use props, not refs
<body> <!-- Prepare a container --> <div id="app"></div> <div id="test2"></div> <!-- Introduce the react core library --> <script type="text/javascript" src="../js/react.development.js"></script> <!-- Introduce react-dom to support react operation DOM --> <script type="text/javascript" src="../js/react-dom.development.js"></script> <!-- Introduce babel to convert jsx to js --> <script type="text/javascript" src="../js/babel.min.js"></script> <script type="text/javascript" src="../js/prop-types.js"></script> <script type="text/babel">/*This time must be text/babel*/ class Person extends React.Component { render() { const {name, age, sex} = this.props return ( <ul> <li>Name: {name}</li> <li>Grade: {age}</li> <li>Gender: {sex}</li> </ul> ) } } Person.prototypes = { name: PropTypes.string.isRequired, sex: PropTypes.string } Person.defaultProps = { sex:'It's not difficult or not a girl', age: 11 } ReactDOM.render(<Person name='andy' age={49}/>, document.getElementById('app')) //shorthand const p = {name:'LDH', age:18, sex:' '} ReactDOM.render(<Person {...p}/>, document.getElementById('test2')) </script> </body> Copy code

Shorthand

<body> <!-- Prepare a container --> <div id="app"></div> <div id="test2"></div> <!-- Introduce the react core library --> <script type="text/javascript" src="../js/react.development.js"></script> <!-- Introduce react-dom to support react operation DOM --> <script type="text/javascript" src="../js/react-dom.development.js"></script> <!-- Introduce babel to convert jsx to js --> <script type="text/javascript" src="../js/babel.min.js"></script> <script type="text/javascript" src="../js/prop-types.js"></script> <script type="text/babel">/*This time must be text/babel*/ class Person extends React.Component { static prototypes = { name: PropTypes.string.isRequired, sex: PropTypes.string } static defaultProps = { sex:'It's not difficult or not to be a girl', age: 11 } state = {} render() { const {name, age, sex} = this.props return ( <ul> <li>Name: {name}</li> <li>Grade: {age}</li> <li>Gender: {sex}</li> </ul> ) } } ReactDOM.render(<Person name='andy' age={49}/>, document.getElementById('app')) //shorthand const p = {name:'LDH', age:18, sex:' '} ReactDOM.render(<Person {...p}/>, document.getElementById('test2')) </script> </body> Copy code

Functional component

<body> <!-- Prepare a container --> <div id="app"></div> <div id="test2"></div> <!-- Introduce the react core library --> <script type="text/javascript" src="../js/react.development.js"></script> <!-- Introduce react-dom to support react operation DOM --> <script type="text/javascript" src="../js/react-dom.development.js"></script> <!-- Introduce babel to convert jsx to js --> <script type="text/javascript" src="../js/babel.min.js"></script> <script type="text/javascript" src="../js/prop-types.js"></script> <script type="text/babel">/*This time must be text/babel*/ function Person (props) { const {name, age, sex} = props return ( <ul> <li>Name: {name}</li> <li>Grade: {age}</li> <li>Gender: {sex}</li> </ul> ) } Person.prototypes = { name: PropTypes.string.isRequired, sex: PropTypes.string } //Defaults Person.defaultProps = { sex:'It's not difficult or not a girl', age: 11 } ReactDOM.render(<Person name='andy' sex=" " age={18}/>, document.getElementById('app')) </script> </body> Copy code

3.ref

  • ref reference method
    • 1. Ref in the form of a string
      • <input ref="input1"/>
    • 2. Ref in callback form
      • <input ref={(c)=>{this.input1 = c}}
    • 3.createRef creates ref container (the latest, recommended writing)
      • myRef = React.createRef() <input ref={this.myRef}/>
  • Callback form ref
    • Inline style function, the function will be triggered twice
      • Modification plan: Defined as a binding function <input ref={this.savaRef}/>

4. Event handling

  • 1. Specify the event processing function through the onXxx attribute (note the case)
    • 1) React uses custom (synthetic) events instead of native DOM events
      • For better compatibility
    • 2) Events in React are handled through event delegation (delegated to the outermost element of the component)
  • 2. Get the DOM element object where the event occurred through event.target
    • Don't overuse ref
    • Indicates that this function will be called immediately after the element is mounted on the page and passed in the rendered DOM element

Seven. Collect form data

  • Classification of components that contain forms
    • 1. Controlled components
      • The value in the form is saved to the state, similar to two-way binding in vue
      • The current input content is obtained through the onChange event, and the current input content is passed in as the value, and it becomes a controlled component at this time
    • 2. Uncontrolled components
      • Take it now

1. Uncontrolled components

<body> <!-- Prepare a container --> <div id="app"></div> <!-- Introduce the react core library --> <script type="text/javascript" src="../js/react.development.js"></script> <!-- Introduce react-dom to support react operation DOM --> <script type="text/javascript" src="../js/react-dom.development.js"></script> <!-- Introduce babel to convert jsx to js --> <script type="text/javascript" src="../js/babel.min.js"></script> <script type="text/javascript" src="../js/prop-types.js"></script> <script type="text/babel">/*This time must be text/babel*/ class Login extends React.Component { handleSubmit = (event) => { event.preventDefault() const {username, password} = this alrt(`The information you are is ${username.value}${password.value}`) } render() { return ( <div> <form action="" onSubmit={this.handleSubmit}> Username: <input ref={c => this.username = c} type="text" name="username"/> Password: <input ref={c => this.password = c} type="password" name="password"/> <button>Login</button> </form> </div> ) } } ReactDOM.render(<Login/>, document.getElementById('app')) </script> </body> Copy code

2. Controlled components

<body> <!-- Prepare a container --> <div id="app"></div> <!-- Introduce the react core library --> <script type="text/javascript" src="../js/react.development.js"></script> <!-- Introduce react-dom to support react operation DOM --> <script type="text/javascript" src="../js/react-dom.development.js"></script> <!-- Introduce babel to convert jsx to js --> <script type="text/javascript" src="../js/babel.min.js"></script> <script type="text/javascript" src="../js/prop-types.js"></script> <script type="text/babel">/*This time must be text/babel*/ class Login extends React.Component { state = { username:'', password:'' } saveUsername = (event) => { this.setState({ username: event.target.value }) } savePassword = (event) => { this.setState({ password: event.target.value }) } handleSubmit = (event) => { event.preventDefault(); const {username, password} = this.state alrt(`Any output value ${username} ---- ${password}`) } render() { return ( <div> <form onSubmit={this.handleSubmit}> Username: <input onChange={this.saveUsername} type="text" name="username"/> Password: <input onChange={this.savePassword} type="password" name="password"/> <button>Login</button> </form> </div> ) } } ReactDOM.render(<Login/>, document.getElementById('app')) </script> </body> Copy code

8. Currying of higher-order functions and functions

  • savaFormData is a higher-order function
  • Higher-order function: If any one of the following two specifications is a higher-order function
    • 1. If A function, the received parameter is a function, then A is a higher-order function
    • 2. If A function, return a function (the return value is a function), then A is a higher-order function
  • What are the higher order functions
    • Promisee
    • setTimeout (timer)
    • arr.map
    • reduce
  • Currying of functions: the function calls and returns a function, and realizes the function encoding form of receiving formal parameters multiple times and processing uniformly
<body> <!-- Prepare a container --> <div id="app"></div> <!-- Introduce the react core library --> <script type="text/javascript" src="../js/react.development.js"></script> <!-- Introduce react-dom to support react operation DOM --> <script type="text/javascript" src="../js/react-dom.development.js"></script> <!-- Introduce babel to convert jsx to js --> <script type="text/javascript" src="../js/babel.min.js"></script> <script type="text/javascript" src="../js/prop-types.js"></script> <script type="text/babel">/*This time must be text/babel*/ class Login extends React.Component { state = { username:'', password:'' } savaFormData = (dataType) => { return (event) => { this.setState({[dataType]: event.target.value}) } } handleSubmit = (event) => { event.preventDefault(); alrt(`Any output value ${username} ---- ${password}`) } render() { return ( <div> <form onSubmit={this.handleSubmit}> Username: <input onChange={this.savaFormData('username')} type="text" name="username"/> Password: <input onChange={this.savaFormData('password')} type="password" name="password"/> <button>Login</button> </form> </div> ) } } ReactDOM.render(<Login/>, document.getElementById('app')) </script> </body> Copy code

9. Life cycle

  • Some stages of components from creation to destruction
  • The react component contains a series of life cycle hooks, which are called at specific times

1. Life cycle stage (old)

  • 1. Initialization phase: first triggered by ReactDOM.render() -----

    • 1.constructor()
    • 2.componentWillMount() ------> Commonly used
      • Generally do some initial things in this hook, such as: start the timer, send network requests, subscribe to messages
    • 3.render()
    • componentDidMount()
  • 2. Update phase: triggered by this.setSate() or re-render of the parent component within the component

    • 1.shouldComponentUpdate()
    • 2.componentWillUpdate()
    • 3.render() -----> one that must be used
    • 4.componentDidUpdate()
  • 3. Uninstallation phase

    • 1.componentWillUnmount() -----> Commonly used
      • Generally do some finishing things in this hook, such as: turning off the timer, unsubscribing to messages

2. Life cycle stage (new)

  • Initialization phase: Triggered by ReactDOM.render() --- first rendering
    • 1.constructor()
    • 2.getDerivedStateFromProps
      • If the value of state depends on props at any time, you can use getDerivedStateFromProps to derive the state
    • 3.render()
    • 4.componentDidMount()
    1. Update phase: Triggered by this.setSate() within the component or re-render of the parent component
    • 1.getDerivedStateFromProps
    • 2.shouldComponentUpdate()
    • 3.render()
    • 4.getSnapshotBeforeUpdate
      • Take a snapshot before updating
    • 5.componentDidUpdate()
    1. Unmount component: triggered by ReactDOM.unmountComponentAtNode()
    • 1.componentWillUnmount()

10.react scaffolding

1. Install scaffolding

  • The first step, global installation: npm i -g create-react-app
  • The second step is to switch to the directory of the project you want to create, and use the command: create-react-app hello-react
  • The third step is to enter the project folder: cd hello-react
  • The fourth step is to start the project: npm start

2. Componentized coding process of functional interface

    1. Split components: split interface, extract components
    1. Implement static components: Use components to achieve static page effects
    1. Implement dynamic components
    • 3.1 Dynamic display of initialization data
      • 3.1.1 Data Type
      • 3.1.2 Data name
      • 3.1.2 Which component is stored in?
    • Interaction (start from binding event monitoring)

11. News subscription-publishing mechanism

1. Tool library: PubSubJS

2. Download: npm install pubsub-js --save (yarn add pubsub-js)

3. Installation

  • import PubSub from'pubsub-js'//import

  • PubSub.subscribe('delete', function(mag, data){ });//Subscribe (receive data)

    • The subscription function has 2 input parameters, the first input parameter is not actually used much, the real data is in the second input parameter
    • Case:
    this.token = PubSub.subscribe('atguigu',(_, data) => { this.setState({keyword: data}) }) ---- In the life cycle of componentDidMount Copy code
  • PubSub.publish('delete', data)//Publish message (publish data)

4. Unpublish

  • PubSub.unsubscribe(this.token)
  • Cancellation in the life cycle of componentWillUnmount

12.React routing

1. Route understanding

  • A route is a mapping relationship (key: value)
  • key: path, value: may be function or component

2. Basic use of routing

  • Clear the navigation area and display area in the page
  • The a tag in the navigation area is changed to the Link tag
  • Route label in the display area for road matching
  • App outermost package or
import React, {Component} from'react' import {Link, Route} from'react-router-dom' import Home from'./components/Home' import About from'./components/About' export default class App extends Component { render() { return ( <div> <div className="row"> <div className="col-xs-offset-2 col-xs-8"> <div className="page-header"><h2>React Router Demo</h2></div> </div> </div> <div className="row"> <div className="col-xs-2 col-xs-offset-2"> <div className="list-group"> <Link className="list-group-item" to="/about">About</Link> <Link className="list-group-item" to="/home">Home</Link> </div> </div> <div className="col-xs-6"> <div className="panel"> <div className="panel-body"> <Route path="/about" component={About}/> <Route path="/home" component={Home}/> </div> </div> </div> </div> </div> ) } } <App>Component import React from'react' import ReactDOM from'react-dom' import {BrowserRouter} from'react-router-dom' import App from'./App' ReactDOM.render( <BrowserRouter> <App/> </BrowserRouter>, document.getElementById('app') ) Copy code

3. Routing components and general components

  • Different writing
General components: <Demo/> Routing component: <Route path="/demo" component={Demo}/> Copy code
  • Different storage location
General components: components Routing component: pages Copy code
  • Different props received
General components: receive whatever is passed Routing component: 3.fixed attributes are received history: go: go(n) goBack: goBack() goForward: goForward() location: {pathname: "/home", search: "", hash: "", state:undefined, key: "2lik3y"} push: push(path, state) replace: replace(path, state) location: pathname: "/home" search: "" state: undefined __proto__: Object match: params: {} path: "/home" url: "/home" Copy code

4. Solve the problem that the refresh style of multi-level path page is lost

  • public/index.html When introducing styles, don t write ./as/(commonly used)
  • public/index.html When importing styles, do not write./Ctrip%PUBLIC_URL% (commonly used)
  • Use HashRouter

5. Fuzzy matching and precise matching of routing

  • The default is fuzzy matching, ([input path] must include [matching path], the order of cuts is the same)
  • Precise matching
    <Route ecact={true} to="about" component={About}>
  • Accurate matching should not be opened casually, it needs to be opened again, which sometimes results in failure to match the secondary route

6.redirect

  • Half of it is written at the bottom of the route registration. If all routes do not match, jump to the route specified by Redirect
  • <Route to="/about" component={About}/> <Route to="/home" component={Home}> <Redirect to="/home"> Copy code

7. Nested routing

  • When registering a child route, write the path value of the parent route
  • Route matching is performed in the order of registered routes

8. Pass parameters to the routing component

  • params parameters
Routing link (carrying parameters): <Link to='/demo/test/tom/18'}>Details</Link> Registered route (declaration received): <Route path="/demo/test/:name/:age" component={Test}/> Use parameters: this.props.match.params Copy code
  • search parameter
Route link (with parameters): <Link to={`/demo/test?name=${item.name}&age=${item.age}`}>Details</Link> Register the route (no need to declare, normal registration is fine): <Route path="/demo/test" component={Test}/> Receiving parameters: this.props.location.search Remarks: The search obtained is urlencoded encoded characters String, need to use querystring to parse the qs plug-in Copy code
  • state parameter
Routing link (carrying parameters): <Link to={{pathname:'/demo/test',state:{name:'tom',age:18}}}>Details</Link> Register the route (no need to declare, normal registration is fine): <Route path="/demo/test" component={Test}/> Receive parameters: this.props.location.state Note: Refresh can also retain the parameters Copy code

9. Programmatic routing and navigation

Use the API on this.prosp.history object to jump, forward, and rewind the operation route

  • this.prosp.history.push()
  • this.prosp.history.replace()
  • this.prosp.history.goBack()
  • this.prosp.history.goForward()
  • this.prosp.history.go()

10.withRouter

  • General components can be processed, so that general components have some apis specific to routing components
  • withrouter is a new formation
  • The business logic is in the class

11. The difference between BrowserRouter and HashRouter

1. The underlying principles are different:

  • BrowserRouter uses H5's history API, which is not compatible with IE9 and below.
  • HashRouter uses the hash value of the URL.

2. Path manifestations are different

  • There is no # in the path of BrowserRouter, for example: localhost:3000/demo/test
  • The path of HashRouter contains #, for example: localhost:3000/#/demo/test

3. Impact on routing state parameters after refresh

  • BrowserRouter has no effect, because the state is stored in the history object.
  • After the HashRouter is refreshed, the routing state parameters will be lost! ! !

4. Remarks: HashRouter can be used to solve some path errors related problems.

12. Antd's on-demand introduction + custom theme

1. Installation dependency: yarn add react-app-rewired customize-cra babel-plugin-import less less-loader 2. Modify package.json .... "scripts": { "start": "react-app-rewired start", "build": "react-app-rewired build", "test": "react-app-rewired test", "eject": "react-scripts eject" }, .... 3. Create config-overrides.js in the root directory //Configure specific modification rules const {override, fixBabelImports,addLessLoader} = require('customize- cra'); module.exports = override( fixBabelImports('import', { libraryName:'antd', libraryDirectory:'es', style: true, }), addLessLoader({ lessOptions:{ javascriptEnabled: true, modifyVars: {'@primary-color':'green' }, } }), ); 4. Remarks: You don t need to introduce styles in the component yourself, that is: import'antd/dist/antd.css' should be deleted Copy code

13.redux

1. What is redux?

  • 1.redux is a js library dedicated to state management
  • 2. It can be used in react, angular, vue and other projects, but it is basically used in conjunction with react
  • 3. Role: centralized management of the shared state of multiple components in the react application

2. Application scenarios

  • A certain component status, other components can also be obtained at any time
  • One component needs to change the state of another component

3.redux workflow

4. 3.core concepts of redux

14. Expansion

1. 2 ways to write setState update state

(1). setState(stateChange, [callback])------object-style setState 1.stateChange is the state change object (the object can reflect the state change) 2.Callback is an optional callback function, which is called after the status update is completed and the interface is also updated (after the render call) (2). setState(updater, [callback])------Functional setState 1. updater is a function that returns a stateChange object. 2. The updater can receive state and props. 4. Callback is an optional callback function, which is called after the status is updated and the interface is also updated (after the render call). summary: 1. Object-style setState is a shorthand for functional setState (syntactic sugar) 2. Principles of use: (1). If the new state does not depend on the original state ===> use the object method (2). If the new state depends on the original state ===> use the function method (3). If you need to get the latest state data after setState() is executed, you must write it in the second callback function Read in number Copy code

2. lazyLoad

LazyLoad for routing components

//1. Dynamically load routing components through React's lazy function and import() function ===> The routing component code will be packaged separately const Login = lazy( ()=> import ( '@/pages/Login' )) //2. Specify through <Suspense> to display a custom loading interface before loading the route package file <Suspense fallback={ < h1 > loading..... </h1 > }> < Switch > < Route path = "/xxx" component = {Xxxx}/ > < Redirect to = "/login"/> </Switch > </Suspense> Copy code

15. Hooks

1. What is React Hook/Hooks?

  • Hook is a new feature/new syntax added by React 16.8.0
  • Allows you to use state and other React features in [function components]

2. 3.commonly used hooks

(1). State Hook: React.useState() (2). Effect Hook: React.useEffect() (3). Ref Hook: React.useRef() Copy code

3. State Hook

(1). State Hook allows functional components to have a state state, and read and write state data (2). Syntax: const [xxx, setXxx] = React.useState(initValue) (3). useState() description: Parameters: Initialize the specified value for the first time and cache it internally Return value: An array containing 2 elements, the first is the current internal state value, and the second is the function to update the state value (4). 2 ways to write setXxx(): setXxx(newValue): The parameter is a non-function value, directly specify the new state value, and use it internally to overwrite the original state value setXxx(value => newValue): The parameter is a function, which receives the original state value, returns the new state value, and uses it internally to overwrite the original state value Copy code

4. Effect Hook

(1). Effect Hook allows you to perform side-effect operations in function components (used to simulate life cycle hooks in class components) (2). Side-effect operations in React: Send ajax request data acquisition Set subscription/start timer Manually change the real DOM (3). Grammar and description: useEffect(() => { //Any operation with side effects can be performed here return () => {//Execute before the component is uninstalled //Do some finishing work here, such as clearing the timer/unsubscribing, etc. } }, [stateValue])//If you specify [], the callback function will only be executed after the first render() (4). UseEffect Hook can be regarded as a combination of the following three functions componentDidMount() componentDidUpdate() componentWillUnmount() Copy code

5. Ref Hook

(1). Ref Hook can store/search tags or any other data in the component in the function component (2). Syntax: const refContainer = useRef() (3). Function: Save the label object, the function is the same as React.createRef() Copy code

4. Fragment

use

<Fragment><Fragment> <></> Copy code

effect

There is no need to have a real DOM root tag. Fragment can pass a key attribute

5. Context

understanding

A communication method between components, commonly used for communication between [ancestor components] and [offspring components]

use

1 ) Create a Context container object: const XxxContext = React.createContext() 2 ) When rendering the subgroup, wrap the xxxContext.Provider outside, and pass data to the descendant components through the value attribute: <xxxContext.Provider value={Data}> Subassembly </xxxContext.Provider> 3 ) Descendant components read data: //The first way: only applies to class components static contextType = xxxContext //declare to receive context this .context //read the value data in the context //The second way: both function components and class components are available <xxxContext.Consumer> { value => (//value is the value data in the context What to display ) } </xxxContext.Consumer> Copy code

note

In application development, context is generally not used, and its encapsulation react plugin is generally used

6. Component optimization

2 problems with Component

  1. As long as setState() is executed, even if the state data is not changed, the component will re-render()

  2. Only the current component re-render(), it will automatically re-render the child component, always the child component does not use any data of the parent component ==> low efficiency

Efficient approach

Re-render() only when the component's state or props data changes

the reason

ShouldComponentUpdate() in Component always returns true

solve

Approach 1: Override shouldComponentUpdate() method Compare the new and old state or props data, return true if there is a change, false if not Approach 2: Use PureComponent PureComponent rewrites shouldComponentUpdate(), and returns true only if the state or props data changes note: It is just a shallow comparison of state and props data, if only the internal data of the data object has changed, return false Do not modify the state data directly, but generate new data PureComponent is generally used in the project to optimize Copy code

7. render props

How to dynamically pass in a structure (label) with content to the inside of the component?

In Vue: Use slot technology, that is, pass the structure <AA><BB/></AA> through the component tag body In React: Use children props: pass in the structure through the component tag body Use render props: pass in the structure through the component label property, and you can also pass in parameters, generally use the render function property Copy code

children props

<A> <B>xxxx</B> </A> {this.props.children} Question: If component B needs the data in component A, ==> can't do it Copy code

render props

<A render={(data) => <C data={data}></C>}></A> A component: {this.props.render(internal state data)} C component: read the incoming data of A component to display {this.props.data} Copy code

8. Error boundary

understanding:

Error boundary: used to capture errors in descendant components and render alternate pages

Features:

It can only capture errors generated in the life cycle of descendant components, not errors generated by own components and errors generated by other components in synthesis events and timers

How to use:

getDerivedStateFromError with componentDidCatch

//Life cycle function, once the background component reports an error, it will trigger static getDerivedStateFromError ( error ) { console .log(error); //Trigger before render //Return a new state return { hasError : true , }; } componentDidCatch ( error, info ) { //Count the errors of the page. Send the request to the background to the console.log(error, info); } Copy code

9. Summary of component communication methods

the way:

props: (1).children props (2).render props News subscription-publishing: pubs-sub, event, etc. Centralized management: redux, dva, etc. conText: Producer-consumer model Copy code

Relationship between components

Parent-child components: props Sibling components (non-nested components): message subscription-publishing, centralized management Grandchildren components (cross-level components): message subscription-publishing, centralized management, conText (less used) Copy code