Learn about React for a day


Read before you read

This article is written in haste, it is a study note, it is an entry level study article. If you’re just getting started, maybe some of these introductory videos are more suitable for you. But if you have some knowledge, like Vue, then video is not suitable. It is suggested that after reading this article, you will have a reflection in your mind, read it deeply in the official website, and some in-depth articles. It is thought that there will be a very good improvement.

A framework is not something you can read a few articles and write a Demo and say you know it. It’s a lot of practice, a lot of digging, a lot of learning. Think hard to master. I just learned React with Vue, which is just the tip of the iceberg. At best, it’s an API porter.

– – QAQ

Initialize the project

Novices still recommend the official scaffolding for initializing a demo project via NPX.

NPX create-react-app Project nameCopy the code

This is the deconstruction of the project in the case of the default generated directory.

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
D -- -- -- -- -- 20.6.15 nor to the publicD -- -- -- -- -- 20.6.15 16:41 SRC-a----          20.6.15     14:21            310 .gitignore
-a---- 20.6.15 14:22 746 package.json -a---- 20.6.15 14:21 2884 README.md -a---- 20.6.15 14:22 526017 yarn.lock Copy the code

Then run the project through NPM or YARN. Executing the shell will automatically open a browser when you see the localhost:3000 render. Now you can open the React gate

#NPM shell command
npm run start

#Yarn shell command
yarn start
Copy the code

React element render -JSX

The template template gets a lot of use in Vue, so if you can write HTML it should be easy for you. React returns the DOM directly from functions. Looks very magical, also led to some partners in the beginning of the time will be a little confused, but if there is a certain basis, in Vue wrote the Render function, I think it is very easy to get started. It looks something like this. It’s essentially a createElement process. Therefore, this template rendering method is called JSX.

import React from 'react';
import './App.css';

function App() {
  return (
 <div className="App">  <h1>How are you</h1>  <p>Today is another hopeful day...</p>  </div>  ); } export default App; Copy the code

React’s JSX template engine is used to render it into the DOM


Variable bindings

In Vue templates, constraints are declared with {{}} curly braces to indicate that the field in the declaration is a JS value, not a text. React uses {} curly braces to make the convention. Then you can use JS in the DOM. Here is a Class component that binds the text value of state to the DOM.

class App extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      text: 'I am wangly19'
 }  }   updateText () {  this.setState({  text: 'I am the handsome Wangly19'  })  }   render () {  return (  <div className="App">  <p>I am a dynamic data: {this.state.text}</p>  <button onClick={ this.updateText.bind(this) }>replace</button>  </div>  )  } } Copy the code
The results of

Conditions apply colours to a drawing

In Vue, if you need to render a node dynamically, you do this with the V-if directive. In React, you use operators to render elements. Compare this with Vue.

The &&(or) operator is used to achieve the same effect as v-if.

– – QAQ

render () {
  return (
    <div className="App">
      <p>I am a dynamic data: {this.state.text}</p>
{{/ *<p v-if="true">2</p>* /}} {true && <p>2</p>}  </div>  ) } Copy the code

The same effect as v-if and V-else can be achieved by using the ternary operators.

– – QAQ

render () {
  return (
    <div className="App">
      <p>I am a dynamic data: {this.state.text}</p>
{{/ *<p v-if="true">2</p>* /}} {true ? <p>true</p> : <p>false</p>}  </div>  ) } Copy the code

The list of rendering

The map method is used to traverse the nodes of some basic data structures.

The value,index, and key can be iterated through the map of the data structure and the node information can be returned in the return.

– – QAQ


The event processing

In JavaScript, you bind an event with onClick.

<button onclick="activeBuff">The activation button</button>
Copy the code

In JSX, the onClick attribute is followed by a JSX render template.

Note that this does not exist under the Class component, requiring the user to manually bind this to the method in the called click event method.

– – QAQ

<button onClick={ this.activeBuff.bind(this}> Activate button </button>
Copy the code

component

We all know that Vue and React are componentized solutions. How do you create a component in React? In the new React release, the React Hooks scheme is introduced. So now the Class component and the Function component are the main ones.

The Class components

The Class component is very simple to create, just create a Class and have it inherit from React.component.render method to return the JSX template.

Also, handle Props via the constructor. And declare the state to initialize an object that mounts Props to super.

class App extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
    }
 }  / / render function  render () {  return (  <div className="App">  <p>I'm a Class component</p>  </div>  )  } } Copy the code

The Function components

With the release of React Hooks, the main focus of development has shifted to function components, but the Class component will still be used in older projects. So study them all. In contrast to the Class component, the function component is very simple. Return a Render template inside the function. As follows:

import React from 'react'

function FunctionDemo () {
  return (
    <div> I'm a function component </div>  ) }  export default FunctionDemo Copy the code

Class Component State Status

This module is based on the hooks that are used to fix the State of the Class component. In React, it is not recommended to change the State value directly. Instead, use setState to update the State.

this.setState({
  default: 'Modified file'
})
Copy the code

Similarly, setState does not change the current value directly. It is an asynchronous function in which you can get the latest state.


If you need to add a calculated value, it is recommended to use the return value form of a function.

The principle here is similar to the return method of Vue component data. If you use object mode, using multiple setStates will be overridden by later tasks, thus executing directly once

– – QAQ

// no
this.setState({ index: this.state.index + 1 });
this.setState({ index: this.state.index + 1 });

// yes
this.setState({ index: this.state.index + 1 });  this.setState({ index: this.state.index + 1 }); this.setState((prevState, props) = > {  return {quantity: prevState.quantity + 1}; }); Copy the code


Component communication

Component communication is one of the most common features in development. So how does React component communication work?

The child component gets the value Props of the parent component

Props allows the child component to get the content passed by the parent component very quickly.

  • 1. Add property names and data to the child components
<ClassDemo name="wangly19"></ClassDemo>
Copy the code
  • 2. Use Props in Class
constructor (props) {
  super(props)
  this.state = {
    defaultText: 'I'm the default text'
  }
} Copy the code
  • Use 3.

Name of the property bound by the parent component of this.props

<p>{ this.props.name }</p>
Copy the code

Define the default Props property

In Vue, you can define a default value for Props, so that the content defined in the default Props is displayed, even if the user does not pass it in.

ClassDemo.defaultProps = {
  name: 'I'm the default name'
  / /... The list of parameters
}
Copy the code

Child component passes parent component

Pass a function through Props, and perform a callback through this.props.[function] when the child component needs to change the value of the parent component.

/ / the parent component
class App extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
 childMessage: '2222222222222222'  }  }   onPropChange (newVal) {  this.setState({  childMessage: newVal  })  }   render () {  return (  <div className="App">  <p>{ this.state.childMessage }</p>  <ClassDemo onPropChange={ this.onPropChange.bind(this) }></ClassDemo> {/ *<FunctionDemo></FunctionDemo>* /} </div>  )  } } Copy the code
import React from 'react';

class ClassDemo extends React.Component {
  constructor (props) {
    super(props)
 this.state = {  defaultText: 'I'm the default text'  }  }   changeText () {  this.props.onPropChange('111111111111111')  }   render () {  return (  <div className="App">  <button onClick={ this.changeText.bind(this) }>Change the text</button>  </div>  )  } } export default ClassDemo; Copy the code
figure

The life cycle

Read the official life cycle introduction, quite concise. The component template is selected and then, when it is ready, you can do some logical operations after the component is loaded.

Town god figure

mount

constructor

The constructor initializes, gets executed first, initializes State and so on.

getDerivedStateFromProps

This is a static method and requires the static attribute in front of it

render

Render function that returns the rendered content and is triggered when the page is updated.

componentDidMount

After the component is mounted, the component is already mounted

update

getDerivedStateFromProps

The component is about to be updated, where the parameters correspond to what was changed before and after, and a Boolean is returned to indicate whether the view needs to be updated.

render

When the view is updated, the Render is updated

getSnapshotBeforeUpdate

GetSnapshotBeforeUpdate output after Render componentDidUpdate, similar to what middleware uses to do some capture operations.

componentDidUpdate

GetSnapshotBeforeUpdate, which has three parameters prevProps, prevState, snapshot, which represents the previous props, the previous state, and snapshot. Snapshot is the value returned by getSnapshotBeforeUpdate

constructor (props) {
  super(props)
  this.state = {}
  console.log('1. Constructor constructor ')
}
 componentDidMount () {  console.log('componentDidMount')  Store.subscribe((a)= > {  this.setState({})  }) }  static getDerivedStateFromProps (nextProps, prevState) {  console.log('getDerivedStateFromProps')  console.log(nextProps, prevState)  return true }  getSnapshotBeforeUpdate (prevProps, prevState) {  console.log(prevProps, prevState)  return 'top: 200' }  componentDidUpdate (prevProps, prevState, snapshot) {  console.log(prevProps, prevState, snapshot) }  componentWillUnmount () {  console.log('componentWillUnmount') }  changeText () {  Store.dispatch({  type: 'changeName'. value: 'I'm the name changed in ClassDemo: wangly'  }) }  render () {  console.log('(3) render function')  return (  <div className="App">  <p>{ Store.getState().redux_name }</p>  { this.state.redux_name }  <button onClick={ this.changeText.bind(this) }>Change the text</button>  </div>  ) } Copy the code

uninstall

componentWillUnmount

Component uninstallation, we can clear some timers, cancel network requests.

Component slot

Slots are not new to Vue; nodes inserted in React are passed as Props. Can be found and rendered by pro1ps.children.

// Parent component
<ClassDemo onPropChange={this.onPropChange.bind(this)} >  <h1>Inserted element</h1>
</ClassDemo>

/ / child component <div className="App">  {this.props.children}  <button onClick={this.changeText.bind(this)}>Change the text</button> </div> Copy the code

The Router routing

Routing is the most important thing for SPA applications, without it, the page would not be an application, only a page. The two could not be more different.

Install the react – the router – the dom – save

# shell
npm install react-router-dom --save
Copy the code

Creating a Routing Mode

In Vue, there are two modes of routing, one is hash and the other is history mode. Create different routers by importing different packages.


// histoty
import { BrowserRouter as Router, Link, Route } from 'react-router-dom';
// hash
import { Link, Route, HashRouter as Router } from 'react-router-dom';
Copy the code

Create a simple route

The Router that comes out of the AS has fast packet routing, and the Link serves as the container of forward behavior. This completes a basic routing container.

The component needs to be configured by Route to be found by Link.

– – QAQ

import React from 'react';
// histoty
import { BrowserRouter as Router, Link, Route } from 'react-router-dom';
// hash
// import { Link, Route, HashRouter as Router } from 'react-router-dom';
 function Page1 () {  return (  <h1>I am a Page1</h1>  ) }  function Page2 () {  return (  <h1>I am a Page2</h1>  ) }  function Page3 () {  return (  <h1>I am the Page3</h1>  ) }  class App extends React.Component {  constructor (props) {  super(props)  this.state = {  }  }   render () {  return (  <div className="App">  <Router>  <ul>  <li>  <Link to="page1">Page1</Link>  </li>  <li>  <Link to="page2">Page2</Link>  </li>  <li>  <Link to="page3">Page3</Link>  </li>  </ul>  <Route exact path="/page1" component={ Page1} ></Route>  <Route exact path="/page2" component={ Page2} ></Route>  <Route exact path="/page3" component={ Page3} ></Route>  </Router>  </div>  )  } } export default App; Copy the code

Routing by value

The param and Query parameters are used for routing parameters. Data is passed by passing an object to to. As you can see, an id has been added to the route to page1 to indicate the value of param’s ID that needs to be passed, along with the declaration of the search text and the state object that passes parameters in various ways. For use in different scenarios.

;<div className="App">
  <Router>
    <ul>
      <li>
 <Link  to={{  pathname: '/page1/10',  search: '?roles=[10, 20] ', state: { name: 'wangly19'}, }}  >  Page1  </Link>  </li>  <li>  <Link to="page2">Page2</Link>  </li>  <li>  <Link to="page3">Page3</Link>  </li>  </ul>  <Route exact path="/page1/:id" component={Page1}></Route>  <Route exact path="/page2" component={Page2}></Route>  <Route exact path="/page3" component={Page3}></Route>  </Router> </div>  Copy the code

Manual jump

When you use the History route, there are times when you need to actively jump to a route without triggering node behavior, so you can use the API to jump to a route. It is used in the same way as Vue.

// Jump to the page
this.props.history. Push (content pixels for parameters and to)this.props.history.push('page1')

// Redirect the page
this.props.history.replace('page2') Copy the code

And of course there’s the go method of hash.

Redux state management

Redux is a global state solution similar to Vuex. Its main function is to store public global state. To facilitate the management of some common configuration parameters, to solve the large volume of services, complex structure of the project to provide good status management.

If the project is not particularly needed, try not to use it.

– – QAQ

Install the story

# shell
npm install redux --save
Copy the code

Create a Store State

See the official Demo, it is very easy to understand. Here’s the official code, so you can see the flow at a glance.

Soul hand-painted
import { createStore } from 'redux'

/ * * * This is a reducer, a pure function with (state, action) => state signature.
 * It describes how an action transforms the state into the next state.  *  * The shape of the state is up to you: it can be a primitive, an array, an object,  * or even an Immutable.js data structure. The only important part is that you should  * not mutate the state object, but return a new object if the state changes.  *  * In this example, we use a `switch` statement and strings, but you can use a helper that  * follows a different convention (such as function maps) if it makes sense for your  * project. * / function counter(state = 0, action) {  switch (action.type) {  case 'INCREMENT':  return state + 1  case 'DECREMENT':  return state - 1  default:  return state  } }  // Create a Redux store holding the state of your app. // Its API is { subscribe, dispatch, getState }. let store = createStore(counter)  // You can use subscribe() to update the UI in response to state changes. // Normally you'd use a view binding library (e.g. React Redux) rather than subscribe() directly. // However it can also be handy to persist the current state in the localStorage.  store.subscribe((a)= > console.log(store.getState()))  // The only way to mutate the internal state is to dispatch an action. // The actions can be serialized, logged or stored and later replayed. store.dispatch({ type: 'INCREMENT' }) / / 1 store.dispatch({ type: 'INCREMENT' }) / / 2 store.dispatch({ type: 'DECREMENT' }) / / 1 Copy the code
  • Create Stoge
// Declare the default State value
const modeStore = {
  redux_name: 'I'm the name declared in Redux: Wangly19'
}
/ / declare Reducer
const reducer = (state = modeStore, action) = > {  return state } // createStore import { createStore } from 'redux'; import reducer from './reducer' const store = createStore(reducer) export default store Copy the code
  • The view to render
import Store from './index'
<p>{ Store.getState().redux_name }</p>
Copy the code
  • Trigger update dispatch
<button onClick={ this.changeText.bind(this}> Change text </button>

// dispatch
changeText () {
 Store.dispatch({  type: 'changeName', Value: 'I am the name changed in ClassDemo: wangly' }) } Copy the code

The premise is that you need to make a declaration on the action method. Action similar to Vuex.

const reducer = (state = modeStore, action) => {
  switch (action.type) {
    case 'changeName':
const newState = {... state}      console.log(state)
 newState.redux_name = action.value  console.log(newState)  console.log(state)  return newState   default:  return state;  } } Copy the code
  • Listen for changes.

As a credential to update the view after the behavior triggers the behavior. Destroy the component when it is logged out.

– – QAQ

componentDidMount () {
  / * ** Callback function* /
  Store.subscribe((a)= > {
 console.log(Store.getState().redux_name)  this.setState({})  }) } Copy the code

Hooks

I am going to write a new article.

– – QAQ

conclusion

Most people learn React by using a Vue approach. I’ve learned that knowing one is knowing the other. It’s not so difficult to learn if you have the foundation. But its documentation is not as comprehensive as Vue’s, and for some reasons. Spent the day organizing some basic study stuff

Give it a thumbs up if you think it helps.

– – QAQ

The resources

The React document

React Lifecycle personal understanding

The react template

The React routing

Redux