The old lifecycle approach

  1. Initialization phase: triggered by reactdom.render () — initial render
    1. constructor()
    2. componentWillMount()
    3. render()
    4. componentDidMount()
    Copy the code
  2. Update phase: triggered by the component’s internal this.setstate () or parent’s render
    / * * * 0. ComponentWillReceiveProps () will be in the parent to render call * / 1. ShouldComponentUpdate () 2. ComponentWillUpdate () 3. The render () 4. componentDidUpdate()Copy the code
  3. Unload components: by ReactDom unmountComponentAtNode triggered ()
    1. componentWillUnmount()
    Copy the code

Conclusion: The old one is obsoletecomponentWillReceiveProps.componentWillMount.componetnWillUpdateThe newstatic getDerivedStateFromProps(props, state).getSnapshotBeforeUpdate

New life cycle

  1. Initialization phase: triggered by reactdom.render () — initial render
    1. constructor()
    2. getDerivedStateFromProps
    3. render()
    4. componentDidMount()
    Copy the code
  2. Update phase: triggered by the component’s internal this.setstate () or the parent’s rerender
    / * * * 0. ComponentWillReceiveProps () will be in the parent to render call * / 1. 2 getDerivedStateFromProps shouldComponentUpdate () 3. The render () 4. getSnapshotBeforeUpdate 5. componentDidUpdate()Copy the code
  3. Unload components: by ReactDom unmountComponentAtNode triggered ()
    1. componentWillUnmount()
    Copy the code

JSX embedded variables

- If the variable is Number,String, or Array, it can be displayed directly. - If the variable is null,undefined, or Boolean, the content is emptyCopy the code

The React – the router – dom routing

2. Route component: receives three fixed attributes history: Go: FN go(n) GOBack: FN goback() goForward: FN goForward() Push: fn push(path,state) replace: fn replace(path,state) location: pathname: "/about" search: "" state: undefined match: params: {} path: "/about" url: "/about"Copy the code

The use of the Switch

Switch package tag improves route matching efficiency (single match)

Strict matching and fuzzy matching of routes

1. Fuzzy matching is used by default. (Note: [input path] must contain [matched path] in the same order.) 2. Enable strict matching: <Route exact={true} path="/about" Component ={about}/> 3. Strict matching Do not enable strict matching. You need to enable strict matching again. In some cases, secondary routes cannot be matchedCopy the code

The use of the Redirect

1. It is written at the bottom of all route registrations. If all routes fail to match, route 2 specified by the Redirect is challenged. <Route path="/about" component={about}/> <Route path="/home" component={home}/> <Redirect to="/about"/> </Switch>Copy the code

Pass parameters to the routing component

Params :<Link to='/demo/test/ Tom /18'> </Link> Register Route :<Route path='/demo/test/:name/:age" Component ={Test}/> Const {id,title} = this.props. Mathch.params 2. Name =tom&age=18'> Details </Link> Route path="/demo/test" component={test}/> Const {search} = this.props. Location Note: Search is a Urlencoded string, queryString parsing is required. < Link to = {{path: '/ demo/test'}, state: {name: "Tom, age: 18}}} > details < / Link > register routing (without declaration, normal registration) : <Route path="/demo/test" Component ={test}/> Received parameter: const {state} = this.props. Location Note: The refresh can also preserve the parameters, which are stored in the history object, and the flush cache is invalidatedCopy the code

API for routing components to generic components

import {Component} from 'react' import {withRouter} from 'react-router-dom' class Header extends Component export Default withRouter(Header) Wrap common components with the withRouterCopy the code

Differences between BrowserRouter and HashRouter

1. The underlying principles are different: BrowserRouter uses the HIstroy API of H5 and is incompatible with IE9 and earlier versions. HashRouter uses the hash value of the URL. 2. Path is represented differently. Effect on route State parameters BrowserRouter has no effect after refreshing. Because state is stored in the history object, a HashRouter refresh will cause the route state parameter to be lost

Hooks

useEffect

  1. In the first timerenderMust be executed once after
  2. If the function is returned, then the next timerenderBefore or componentunmountThe return function code must be run once before
  3. If a dependent array is specified and is not empty, it is reruned whenever every element in the array changes
  4. If the array is empty, it is executed only once on the first render
  5. If state is updated in useEffect and no dependent array is specified, or state exists in a dependency array, an infinite loop is created

useState

  1. Every time a functional component is re-rendered [count,setCount] = useState(1).setCountThey’re all equal

Redux

  1. throughreduxthecreateStore(reducer)Create a store
  2. throughstore.dispatchdistributedaction
  3. throughstore.getState()To obtainreducerThe state of
  4. throughstore.subscribe(fn)Subscribe to dispatch event, state change triggers update

Functional component

  1. Functional components are re-executed, and local variables (functions, objects) within a method are not equal

Generator

Function * foo() {console.log("111"); // Function * foo() {console.log("111"); yield "Hello"; console.log("222"); yield "World"; console.log("333"); yield "coderwhy"; console.log("444"); } // iterator: const result = foo(); console.log(result); Const res1 = result.next(); // const res1 = result.next(); // console.log(res1); // const res2 = result.next(); // console.log(res2); // const res3 = result.next(); // console.log(res3); // const res4 =result.next(); // console.log(res4); GenerateNumber () {function* generateNumber() {for (var I = 1; i <= 10; i++) { yield i; } } // const numIt = generateNumber(); // console.log(numIt.next().value); Function * bar() {console.log("1111"); function* bar() {console.log("1111"); const result = yield new Promise((resolve, reject) => { setTimeout(() => { resolve("Hello Generator"); }, 3000); }); console.log(result); } const it = bar(); it.next().value.then(res => { it.next(res) })Copy the code

record

SetState Synchronization asynchronous

  1. setStateAsynchronous in composition time and life cycle, the asynchronous here is actually batch update, to optimize performance

2. SetState is synchronized in setTimeout and native event 3. In setState(fn,callback) it is synchronized

The React development project encountered problems

The
tag is not allowed to play music while the page is open

/** * audio tag events * onEnded when the song isPlaying * onTimeUpdate when the song isPlaying milliseconds * audio. CurrentTime when the song isPlaying milliseconds */ const [isPlaying, setIsPlaying] = useState(false) useEffect( () => { audioRef.current.src = getPlaySong(currentSong.id) audioRef.current.play().then(res=>{ setIsPlaying(true) }).catch( err=> { setIsPlaying(false) }) },[currentSong]) const playMusic = useCallback(() => { setIsPlaying(! isPlaying) isPlaying ? audioRef.current.pause() : audioRef.current.play() },[isPlaying])Copy the code

Css Model tips

To reference CSS class selectors or ID selectors in TSX, you need to install typescript-plugin-CSS-modules

npm install typescript-plugin-css-modules -D
Copy the code

Then add the configuration in tsconfig.json

"CompilerOptions ":{"noImplicitAny": false,// No type is set. "plugins": [{"name": "typescript-plugin-css-modules" } ] }Copy the code

At the same time, create.vacode/settings.json in vscode’s current project root directory

{
    "typescript.tsdk": "node_modules/typescript/lib",
    "typescript.enablePromptUseWorkspaceTsdk": true
}
Copy the code

react-i18next

npm install react-i18next i18next --save
Copy the code

Redux middleware formula

Const middleware = (store) => (next) => (action) =>{}, as follows, the middleware that prints logs

import { Middleware } from "redux" const actionLog: Middlleware = (store) => (next) => (Action) => {console.log("state current ", store.getState()) console.log("fire Action ", Action) next(action) console.log("state update ", store.getState())}Copy the code

Load HTML in JSX

dangerousllySetInnerHTML

<div dangerouslySetInnerHTML={{__html:'<span>abc<span>'}}></div>
Copy the code

Centos docker installation

Yum update yum install epel-release -y yum clean all yum list yum install docker-io -y systemctl start docker Docker info // View the startup resultCopy the code

Docker Ari Cloud Image Accelerator

  1. Open the official website of Aliyun and log in
  2. Click on the top rightThe console
  3. Open theProducts and Services, the choice ofContainer Service Image

4. Click the sidebarMirror tool: Mirror accelerator, according to the operation document