React Environment Setup

Environmental installation

  1. Install nodejs

  2. Install react scaffolding

    npm install create-react-app -g
    Copy the code

Create a project

npx create-react-app my-app

cd my-app

npm start
Copy the code

The project structure

The React loading process

The React entry is in index.js

App.js is loaded as a component in index.js

Once loaded, render into HTML

index.js

import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; /* import App from './App'; /* Import reportWebVitals from './reportWebVitals'; ReactDOM. Render (< react. StrictMode> <App /> </ react. StrictMode>, /* ReactDOM root content, The JSX syntax used */ document.getelementById ('root') /* specifies the binding object of the ReactDOM */); // If you want to start measuring performance in your app, pass a function // to log results (for example: reportWebVitals(console.log)) // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals reportWebVitals();Copy the code

App.js

import logo from './logo.svg'; /* import image path */ import './ app.css '; Function App() {return (<div className="App"> <header className=" app-header "> <img src={logo} className="App-logo" alt="logo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ); } export default App;Copy the code

The React view layer

JSX grammar

Is the extension syntax of basic JS

JSX describes the UI structure

const element = (
  <h1 className="greeting">
    Hello world!
  </h1>
)
Copy the code

Will be converted to React elements inside React

// The structure is simplified
const element = {
  type:'h1'.props: {className:'greeting'.children:'Hello,world! '}}Copy the code

React element rendering

ReactDOM.render(
  <React.StrictMode>
    <App />	
  </React.StrictMode>./* ReactDOM root content, using JSX syntax */
  document.getElementById('root') /* Specifies the binding object for ReactDOM */
);
Copy the code

component

The React component encapsulates React elements and is the basic unit of React application composition and reuse.

component = (props) = > element
Copy the code

A component is like a function that accepts props and returns an element

The React component must operate as a pure function

Pure functions

  1. Returns the same result for the same input parameter
  2. No side effects (Side effects: When a function is called, it returns an additional effect on the calling function in addition to the value of the function)

Why do you say like? Because while the component is running, it needs to be changed based on some network request. It is difficult to avoid side effects, and we need to follow the React specification when performing such operations.

Components can be divided into two categories: function components and class components

Function component

const ArticleList = (props) => { const { articles } = props; Item.map ((item) => {const {id, title} = item; return <div key={id}> {title}</div>; }); };Copy the code

Class components

The render method must be overridden in the class component

class ArticleList extends React.Component { render() { const { articles } = this.props; return articles.map((item) => { const { id, title } = item; return <div key={id}> {title}</div>; }); }}Copy the code

Passed in when called

const articles = [
  { id: 1, title: 'Article 1' },
  { id: 2, title: 'Article 2' },
  { id: 3, title: 'Article 3' },
];

function App() {
  return <ArticleList articles={articles} />;
}

Copy the code

React requires that a key be specified when rendering a list. If it is not specified, a warning error will be reported

React determines whether elements need to be reused based on the same or different keys for performance purposes. If keys are the same, elements are reused to improve performance.

state

The use of state

We pass in fixed arguments and get static elements, but what if we want our React element to be somewhat variable?

We can use state to make our elements dynamic

It is important to note that state can only be used in class components, not function components.

Suppose we need to make a time component that displays in real time

We can create it with the following example

We’ve defined a state here

Update the data with the setState method, which re-renders the element after updating the data

Realize the dynamic display of time

import React, { Component } from 'react'; export default class Clock extends Component { constructor(props) { super(props); this.state = { date: new Date() }; } componentDidMount() { this.timerID = setInterval(() => this.tick(), 1000); } componentWillUnmount() { clearInterval(this.timerID); } tick() { this.setState({ date: new Date(), }); } render() { return ( <div> <h1>Current Time: {this.state.date.toLocaleTimeString()}.</h1> </div> ); }}Copy the code

Component execution flow

Page display effect

SetInterval () is used to access an external API, which is what we call a side effect, but we put the side effect code in the life cycle function, which is called only once, but the render function cannot have side effect code.

The life cycle

Since state can only be used in a class component, not a function component, a function component is stateless, and a class component can be stateful.

This uses the lifecycle function in the class component

ComponentDidMount () is a lifecycle function called once the element is mounted

ComponentWillUnmount () is the lifecycle function called when an element is unmounted

Lifecycle methods are defined in class components; there is no concept of lifecycle in function components

This mainly looks at the several life cycle in bold black, these are commonly used life cycle methods, others are not commonly used, can not pay attention to

setState()

The setState() API is used to make changes during status updates. You cannot directly access the state attribute to make changes

When we modify the state via setState(), if the new state depends on the current state, instead of passing an object parameter to setState(), we need to pass a function that takes two parameters, the first parameter is the state of the current component, and the second parameter is the latest props of the component. This is due to the setState() trigger mechanism of the React internal component

SetState () does not overwrite all parameters, but changes them locally

Props: Properties that a parent component passes to a child component, read-only inside the child component

State: State maintained internally by the component, which can be modified by setState()

Form

The controlled components

React controls the management logic for values and value changes in forms

Event binding via functions

Update values through state

Uncontrolled component

The input component here is strongly bound via ref

Create a ref in the construct

Then bind in the render

Combinatorial usage of components

The components we just created are all a whole inside, but we want to make them look like normal tag elements with child elements inside, which involves component composition.

As you can see from this example, the internal child elements are passed to the component as props. Children.

React creates a hole in the component, but sometimes a hole is not enough.

If we want to pass multiple components, we can pass them as props. If we want to pass multiple components, we can pass them as props

Hooks

React16.8. Hooks are a function that encapsulates the state management logic of function components in React.

Hooks can only be used in function components, not in class components

Stake Hook

This is the most straightforward and basic function for managing state

const [state,setState] = useState(initialState);
Copy the code

useState()

The initial value of the state parameter is received

Returns an array whose first element is the state and whose second element is a method that modifies state.

The name of the return value can be arbitrarily chosen.

function AddPostForm(props){

  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');

  const handleChange = (e) => {
    if (e.target.name === 'title') {
      setTitle(e.target.value)

    } else if (e.target.name === 'content') {
      setContent(e.target.value)
    }
  };

  const handleSave = async () => {
    if (title.length > 0 && content.length > 0) {
      console.log(title, content)
    }
  };

  return (
      <section>
        <h2>Add a New Post</h2>
        <form>
          <label htmlFor="title">Post Title:</label>
          <input
            type="text"
            id="title"
            name="title"
            value={title}
            onChange={handleChange}
          />
          <label htmlFor="content">Content:</label>
          <textarea
            id="content"
            name="content"
            value={content}
            onChange={handleChange}
          />
          <button type="button" className="button" onClick={handleSave}>
            Save Post
          </button>
        </form>
      </section>
    );
};
Copy the code

So that’s useState()

const [title, setTitle] = useState('');
const [content, setContent] = useState('');
Copy the code

It is worth noting that we could also write individual states as objects, but this would replace the entire state when using setState(), not locally as in a class component.

const [{title,content},setState] = useState({
    title:'',
    content:''
})
Copy the code

Effect Hook

When we mentioned class components earlier, the side effect code of the component is referred to in the lifecycle function of the component. Effect Hook can also solve this problem.

useEffect(()=>{effectFn(); return clearFn},[...dependencies])Copy the code

UseEffect () takes two arguments, the first a function and the second an array type argument

Where effectFn is the function that we’re going to execute with side effect logic, and the return value here is clearFn and we can do some side effect clearing logic in clearFn. This return function, clearFn, is first executed every time useEffect() is executed, and is also executed when the component is uninstalled.

The second argument is optional. If not specified, effectFn is executed every time useEffect() is executed. However, if useEffect() is specified, effectFn is executed only when a,b, and C change. If an empty array is passed in, effectFn is executed only once.

UseEffect () is executed every time a component is rendered, but does not mean that effectFn will be executed.

The sample

function App() {
  const [articles, setArticles] = useState([])

  useEffect(()=> {
    const fetchArticles = async () => {
      try{
        const response = await client.get('/fakeApi/posts');
        console.log(response)
        setArticles(response.posts);
      }catch(err){
        console.error(err)
      }
    }

    fetchArticles();
  }, [])

  return (
    <div>
      <ArticleList articles={articles}/>
    </div>
  )

}
Copy the code

other

React provides several other hook apis in addition to the two most commonly used

React (docschina.org)

Custom hooks

Custom hooks must begin function names with the word “use” to encapsulate functions of general logic

import { useEffect } from 'react';
const useMounted = (fn:()=>void) => {
    useEffect(()=>{
        fn();
    },[]);
};
Copy the code

This encapsulates a function that is executed only once at load time;

import React, { useEffect,useState } from 'react';

function useCurrentDate(){
  const [date, setCurrentDate] = useState(new Date());

  const tick = () => {
    setCurrentDate(new Date())
  }

  useEffect(() => {
    const timer = setInterval(()=>{tick()}, 1000)
    return () => {
      clearInterval(timer)
    }
  }, [])

  return date;
}

export default function Clock() {

  const date = useCurrentDate();

  return (
    <div>
      <h1>Current Time: {date.toLocaleTimeString()}.</h1>
    </div>
  );
}
Copy the code

This example creates a custom hook that encapsulates the date changes independently into a reusable hook.

The rules

Rules for using hooks:

  1. We can only call a hook from a function component, a custom hook
  2. A hook can only be called in the top-level control flow of a function

Neither of these examples counts as a top-level control flow

Why Hook?

  1. Using hooks allows us to reuse component state management logic
  2. The future of React

Before hook, we in the development of the application of the React time, a large number of using class components, but the class component has some own limitations, such as life cycle method, this problem leads to the complexity of the component class is much higher than the function component, this also gives the React to do some performance optimization, do some of the more advanced features a lot of obstacles, So React introduced features like Hook to make React components lighter.