Class component lifecycle hook functions

constructor(props)

The constructor of the class component, which is executed first, initializes state and binds this to the event

constructor(props) {
    super(props)
    this.state = {
      name: 'tom'
    }
    this.eventHandler = this.eventHandler.bind(this)
}
Copy the code

getDerivedStateFromProps(props, state)

Is called before the Render method, either during the mount or update phase, and exists for one purpose only: to let the component update state when the props changes

static getDerivedStateFromProps(props, State) {console.log(' here you can get props after the change ') console.log(' this is triggered when rendering and props change for the first time ') return state}Copy the code

shouldComponentUpdate(nextProps, nextState)

Only in the update phase, the first render is not called before render, and the function returns the total Boolean value to decide whether to continue render

ShouldComponentUpdate (nextProps, nextState) {console.log(' If false, no render update ') return true}Copy the code

render()

A function executed during the rendering phase of the component’s life cycle that returns the value that the component wants to render VirtualDOM

render() {
    return (
        <div>hello</div>
    )
}
Copy the code

getSnapshotBeforeUpdate(prevProps, prevState)

Executed after render(), but before output to the DOM, to take a pre-render snapshot. When we want to retrieve the last DOM state before the current update, we do this here, and the return value is retrieved from the third parameter in the componentDidUpdate method, meaning that we can retrieve this value before doing anything else after the component is updated.

getSnapshotBeforeUpdate(prevProps, PrevState) {console.log('getSnapshotBeforeUpdate after render before DOM update ') console.log(' You can get the dom before update here ')}Copy the code

componentDidUpdate()

Is called immediately after a DOM update, not the first rendering. We can manipulate the rendered DOM in this function

ComponentDidUpdate () {console.log('componentDidUpdate DOM is updated after the first rendering does not execute ') console.log(' here you can get the updated DOM')}Copy the code

componentDidMount()

Called after the component is mounted

ComponentDidMount () {console.log(' componentDidMount for the first time ')}Copy the code

componentWillUnmount()

Is called before the component is uninstalled and destroyed, where we can clean up things like timers within the component, pending requests, etc

ComponentWillUnmount () {console.log(' before component destruction ')}Copy the code

Controlled forms and uncontrolled forms

According to the state association between form and state data, it can be divided into controlled components and uncontrolled components

  • Controlled forms: The values in a form control are managed by the component’s state object, which stores values that synchronize state with the values in the form control

  • Uncontrolled forms: The value of a form element is managed by the DOM element itself

Controlled forms are similar to Vue’s bidirectional binding

Two-way data binding means that the component class updates the state, the DOM state updates synchronously, the DOM changes the state, and the component class updates synchronously. Component <=> view.

To implement two-way data binding, you need form elements and state objects.

A controlled form

The values in the form control are managed by the component’s state object. The stored values in the state object are synchronized with the values in the form control. When the form changes, the state changes as well.

class App extends Component {
  constructor () {
    this.state = { username: "" }
    this.nameChanged = this.nameChanged.bind(this)
  }
  
  nameChanged (e) {
    this.setState({username: e.target.value})
  }
  render() {
    return (
      <form>
        <p>{this.state.username}</p>
        {/*  */}
        <input type="text" value={this.state.username} onChange={this.nameChanged}/>
      </form>
    )
  }
}
Copy the code

Uncontrolled form

The value of a form element is managed by the DOM element itself.

class App extends Component {
  constructor () {
    this.onSubmit = this.onSubmit.bind(this)
  }
  onSubmit(e) {
    console.log(this.username.value)
    e.preventDefault();
  }
  render(
    <form onSubmit={this.onSubmit}>
      <input type="text" ref={username => this.username = username}/>
    </form>
  )
}
Copy the code

Getting component instances

The component instance can be obtained by ref and createRef(), which can be used to obtain the tag DOM

class Input extends Component {
  constructor() {
    super()
    this.inputRef = React.createRef()
  }
  render() {
    return (
      <div>
        <input type="text" ref={this.inputRef} />
        <button onClick={() => console.log(this.inputRef.current)}> button </button>
      </div>
    )
  }
}
Copy the code

routing

CNPM install react-router-dom

You must import a path component (BrowserRouter or HashRouter), and use BrowserRouter or HashRouter to include everything

There is no difference between the two components in the development environment, but the difference in the production environment is that hash will have a hash sign on the path, while Browser does not

import React from 'react'; import { BrowserRouter, Route, Link } from 'react-router-dom'; Function Index() {return <div> </div>; } function News() {return <div> News </div>; } function App() {return (<BrowerRouter> <div> <Link to="/index"> </Link> <Link to="/news"> </Link> </div> <div> <Route path="/index" component={Index}/> <Route path="/news" component={News}/> </div> </BrowerRouter> ); }Copy the code

Nested routing

The child routing component obtains the path to the parent routing component using props. Mating. path

Function News(props) {return (<div> <div> <Link to={' ${props.match.url}/company '}> Company News </Link> <Link To = {` ${props. Match. Url} / industry `} > industry news < / Link > < / div > < div > < the Route path = {` ${props. Match. The path} / company `} component={CompanyNews} /> <Route path={`${props.match.path}/industry`} component={IndustryNews}/> </div> </div> ); } function CompanyNews() {return <div> IndustryNews() {return <div> IndustryNews </div>}Copy the code

Routing and the cords

{/* Parent routing component */} <Link to={' /detail? Id =${item.id} '}>{item.title}</Link> {/* child route Component */} import URL from 'url' class Detail extends Component { constructor(props) { super(props); const { query } = url.parse(this.props.location.search, true); console.log(this.props.location.serach); / /? id=1 console.log(query); // {id: 1} } }Copy the code

Route redirection

Use Redirect components

import { Redirect } from 'react-router-dom';

class Login extends Component {
  render() {
    if (this.state.isLogin) {
      return <Redirect to="/"/>
    }
  }
}
Copy the code

exact

The exact matching mode is used. In the non-exact mode, ‘/’ matches all routes starting with ‘/’

If you do not use exact, /about matches both index and about components

<Route path="/" exact component={IndexPage} />
<Route path="/about" exact component={AboutPage} />
Copy the code

Link component

The Link component handles functions like a Link (it generates an A tag in the page), but the setup here is important. The react-router-dom intercepts the default action of the actual A tag and then processes it based on any routing mode used (Hash or HTML5). The URL is changed, but the request does not occur, and the corresponding component is displayed at the specified location according to the Settings in Route

The to attribute is similar to href in the A tag

NavLink

NavLink is similar to Link, but it provides two special properties to handle page navigation

activeStyle

The style in activeStyle is activated when the current URL matches the to in NavLink, that is, when selected

activeClassName

Similar to activeStyle, but with className activated

<NavLink to="/" exact activeStyle={{ color: </NavLink> </NavLink to="/about" exact activeClassName="active-class" >Copy the code