The front-end continent is a newly emerging plate in the technology industry in recent years. With people’s increasing interaction and performance of websites, there are countless summoners who go to the front-end continent to practice Javascript. There are so many strange people and different people in the front-end, so the methods of practicing Javascript are all different, and the future of the Web front-end is still uncertain. Fortunately, the core groups in the front circle have become popular. React, Vue and Angular are the three pillars, and they are the leaders. Today’s story starts from React Valley

Each front-end summoner in React Canyon is bronze, silver, gold, platinum, Diamond, Star, and King, according to the understanding of React stack and front-end, which corresponds to the seven modules in this series

  1. Stubborn bronze
    • The default summoner already has the initial stage for entering the canyonES6.nodejsOn the basis of
    • usecreate-react-appTo establishReactThe development environment
    • learningReactBasic gameplay in the world, like componentization,JSX, event listening, internalstate, a component ofprops, life cycle function, etc
    • This article mainly introducesReactThe basic knowledge that bronze rises silver to need, see you silver
  2. Order of the silver
    • To the silver section, the basic are the basic operation, will not appear lovely standing in the local tower was killed under the situation
    • We need to buy a skin to improve the look and practice
    • Learn to use Ant Financialant-designThe use of
  3. The glory of gold

    • At this stage, the summoner is rightReactWith a basic understanding, we need to improve our overall view if we want to further improve our position
    • Learn to useReact-Router4To give us multifaceted capabilities
    • Learn how to useBrowserRouter.Router.LinkComponents such as
    • Learn how to useReduxWork with your teammates to improve your perspective
    • Understand single data flow development patterns andReduxSuch asdispatch.action.reducers
    • usereact-reduxBetter andReduxWith a sense of the big picture, platinum is also very easy
  4. Honorable platinum

    • Many summoner card in platinum, because platinum wants to diamond, need to understand more details and principles
    • ReactThe principle of analyzing
    • Have a deep understanding of the principles of your skills, essential for diamonds
  5. Eternal diamond

    • The diamond stage begins in omen mode, and the summoner’s skill pool needs to be deep enough to advance further and to have a deeper understanding of what he or she is good at
    • ReduxMiddleware mechanism to implement your own middleware
    • Common React performance optimization methods
    • Server side rendering
    • ReduxOther data solutions such asmobx.dva
  6. The ultimate star yao

    • This section is already strong on its own. The React library is only targeted at the next layer, so it needs to understand the underlying principles
    • ReduxPrinciple analysis + implementation of their ownRedux
    • React-Router+ implement your ownReact-Router
    • WebppackAnalysis of working mechanism and principle
    • BabelAnalysis of working mechanism and principle
  7. Most of the king
    • I’m already a top summoner when I reach the top king, and I’m famous in the React Valley. I heard that there is also a legendary king of Glory position, which I can’t reach in my life, and I can’t teach you
    • At this stage, THE only book I recommend is “Programmer’s Health Guide”. It’s only a matter of time to keep your body and mind healthy and become a king of glory

Redux+React Router+Node.js Redux Router+Node.js

Below begins our body of text, a recalcitrance of bronze

  1. Environment set up
  2. The first component
  3. Component nesting and property passing
  4. State handling
  5. The life cycle

Environment set up

By default, you already have the Node environment. Install the scaffolding first

npm install create-react-app -gCopy the code

Then the project is set up and started

create-react-app bronze
cd bronze
npm startCopy the code

See the diagram below, which means the first React application has been launched

We open the SRC directory

SRC ├─ app.css ├─ app.js ├─ index.css ├─ index.js ├─ logo.svg ├─ registerServiceworker.jsCopy the code

Index.js is the entry file that imports React and ReactDom, and then renders a component App on top of the #root element

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />,document.getElementById('root'));Copy the code

Then focus on app.js as the concrete content of our component


import React, { Component } from 'react'

class App extends Component {
  render() {
    return (
      <div className="App">
        <p>
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>); }}export default App;Copy the code

This is basically the simplest React component, and there are several steps to implement the React component

  1. import React
  2. Create a new class and inheritReact.Component.ReactEach component can be written as a class
  3. Of the classrenderThe function returns the value, which is what is displayed on the page
  4. renderIt’s returning something weird, ostensiblyhtmlActually,BabeltheJSXintoReact.createElememtTo perform the
  5. Due to theJSXThe essence is JS,classIs the js keyword, so useclassNameInstead of
  6. If you want to be inJSXRender variable, use{}Package can be

JSX is a JSX object, which is rendered into a DOM using the reactdom.render method

// JSX <div className="App"> <p>hello react</p> </div> "App" }, React.createElement( "p", null, "hello react" ) )Copy the code

The first component

We implement our first component and modify app.js to

import React, { Component } from 'react'

class App extends Component {
  render() {
    const level='The Greatest'
    return (
      <div>
        <h2>Our goal is {level}</h2>
      </div>)}}export default AppCopy the code

Since JSX is essentially JS, we can use js expressions in {}, such as ternary, functions, variables, etc., and can also map arrays to lists. We changed the code to

import React, { Component } from 'react'

class App extends Component {
  render() {
    const level='The Greatest'
    const isKing = true

    const title = isKing
                    ? <p>Early to bed and early to rise, play wise</p>
                    : <h2>Our goal is {level}</h2>

     const wordList = ['My grandson is coming.'.'Bewitched'.'The path to learning lies under your feet']
    return (
      <div>
        {title}
        {isKing ? <p>I am the king</p>: null}
        <ul>
          {wordList.map(v=><li key={v}>{v}</li>)}
        </ul>
      </div>)}}export default AppCopy the code

One thing to note here is that in render, if multiple elements return, there must be a parent element wrapped around it, otherwise there will be an error

We can copy JSX to variables outside of return. We can also use a triple expression inside {} in JSX. You can change isKing to false and try it out

Then there is the render list. We use the map function to map directly to the JSX array. Remember that each element in the list has a key property, which we’ll talk about when we talk about the virtual DOM

Component nesting and property passing

If we continue to design our application, let’s design a Tank component that can be used directly in the App and pass a property inside the component that we can get with this.props. Key


import React, { Component } from 'react'

class App extends Component {
  render() {
    const level='The Greatest'
    const isKing = true

    const title = isKing
                    ? <p>Early to bed and early to rise, play wise</p>
                    : <h2>Our goal is {level}</h2>
    return (
      <div>
        {title}
        {isKing ? <p>I am the king</p>: null}
        <Tank name='Cheng Bite gold'></Tank> 
      </div>)}}class Tank extends Component {
  render() {
    return (
        <div>
          <h3>{this.props. Name} is a tank</h3>
        </div>)}}export default AppCopy the code

If our component only has a render method, we can also write a function as props, which is the parameter of the function. We call this component stateless component

function Tank(props){
  return (
    <div>
      <h3>{props. Name} is a tank</h3>
    </div>)}Copy the code

In this way, we can divide the application into multiple components and use the form of building blocks to assemble the application. However, none of the existing components can be changed. Next, we will learn the React state management, that is, state

React State management and event listening

We initialize state in the constructor function, which is essentially a normal JS object, and then modify state by calling this.setState. Each time setState, You can use onClick to bind a function that listens for user events. Without further ado, look at the code

class App extends Component {
  constructor(props){
    super(props)
    this.state = {
      isKing:true
    }
    this.handleClick = this.handleClick.bind(this)
  }
  handleClick(){
    this.setState({
      isKing:!this.state.isKing
    })
  }
  render() {
    const level='The Greatest'

    const title = this.state.isKing
                    ? <p>Early to bed and early to rise, play wise</p>
                    : <h2>Our goal is {level}</h2>
    return (
      <div>
        <button onClick={this.handleClick}>Am I</button>
        {title}
        {this.state.isKing ? <p>I am the king</p>: null}
        <Tank name='Cheng Bite gold'></Tank> 
      </div>)}}Copy the code

One of the points we need to focus on is constructor, which we call the constructor. The component initialization state is placed here, isKing is set to true, and then on the button element onClick, handleClick is performed. Inside the handleClick, Call this.setState to modify isKing

The constructor bind function forces handleClick’s this to be bound to the component, otherwise onClick will get the this reference. There are other ways to fix this without writing the bind line

import React, { Component } from 'react'

class App extends Component {
  constructor(props){
    super(props)
    this.state = {
      isKing:true
    }
    this.handleClick = this.handleClick.bind(this)}// Manually bind from constructor
  handleClick(){

    this.setState({
      isKing:!this.state.isKing
    })
  }
  // Pass the arrow function when binding
  handleClick1(){
    this.handleClick()
  }
  // The header function is defined
  handleClick2 = (a)= >{
    this.handleClick()
  }
  // bind directly when onClick
  handleClick3(){
    this.handleClick()
  }
  render() {
    const level='The Greatest'

    const title = this.state.isKing
                    ? <p>Early to bed and early to rise, play wise</p>
                    : <h2>Our goal is {level}</h2>
    return (
      <div>
        <button onClick={this.handleClick}>Am I</button>
        <button onClick={()= >Enclosing handleClick1 ()} > I 1 point</button>
        <button onClick={this.handleClick2}>I for 2</button>
        <button onClick={this.handleClick3.bind(this)}>My 3</button>
        {title}
        {this.state.isKing ? <p>I am the king</p>: null}
        <Tank name='Cheng Bite gold'></Tank> 
      </div>)}}Copy the code

The life cycle

The React component has a different hook function at different times. For example, after a component is loaded, the React componentDidMount hook function is executed


class App extends Component{
  componentDidMount(){
    console.log('Component rendered complete')
  }
  render(){
    console.log('Component rendering')
    return <h2>Stubborn bronze</h2>}}// The component is being rendered
// The component is renderedCopy the code

React executes different functions in different phases. I found a diagram on the Internet that clearly shows when functions in each lifecycle are executed.

class App extends Component {
  constructor(props){
    super(props)
    this.state = {
      isKing:true
    }
    this.handleClick = this.handleClick.bind(this)
    console.log('Constructor App, initialization is performed first')
  }
  handleClick(){
    this.setState({
      isKing:!this.state.isKing
    })
  }
  componentWillMount(){
    console.log('componentWillMount, Component App ready to render ')
  }
  componentDidMount(){
    console.log('componentDidMount, component App rendered ')
  }
  shouldComponentUpdate(){
    console.log('shouldComponentUpdate, determine if App components should render, default returns true')
    return true
  }
  componentWillUpdate(){
    console.log('componentWillUpdate, component App is ready to update ')
  }
  componentDidUpdate(){
    console.log('componentDidUpdate, component App updated ')
  }
  render() {
    const level='The Greatest'

    const title = this.state.isKing
                    ? <p>Early to bed and early to rise, play wise</p>
                    : <h2>Our goal is {level}</h2>
    const wordList = ['My grandson is coming.'.'Bewitched'.'The path to learning lies under your feet']
    console.log('Component App is rendering')
    return (
      <div>
        <button onClick={this.handleClick}>Am I</button>
        {title}
        {this.state.isKing ? <p>I am the king</p>: null}

        <ul>
          {wordList.map(v=><li key={v}>{v}</li>)}
        </ul>
        <Tank name='Cheng Bite gold'></Tank> 
      </div>)}}// First load print
constructorApp constructor, init componentWillMount, component App ready to render component App is rendering componentDidMount, ShouldComponentUpdate: shouldComponentUpdate: shouldComponentUpdate: shouldComponentWillUpdate: shouldComponentWillUpdate: shouldComponentWillUpdate: shouldComponentWillUpdate The component App is rendering componentDidUpdate, the component App is updatedCopy the code

In addition to the above, there are other things to note

  1. React16The addition ofcomponentDidCatchLife cycle, used to handle errors
  2. shouldComponentUpdatereturnfalse, then the component will not render
  3. If it’s a child component, there’s anothercomponentWillReceiveProps
  4. Component uninstallation yescomponentWillUnmountTo clean up resources
  5. Take advantage of the life cycle and do different things at different stages

    If you can see here, that’s trueReactTrue love. Congratulations. You’re order silver. Get your badge

Redux+React Router+Node.js

Next period: order silver – use ant-design UI library, have a message, we can also open black, together on the king