React- Learn the route

  • To learn hook, you must master the form of class-based components.

1.JSX

  • Any valid JS code can be placed inside {}
  • You can return a JSX expression
  • The React component must be wrapped in the outermost layer of the component

Sometimes you can use the Fragement tag when the outermost element is not available

2. Components & Props

  • The React. CreatClass method is used to generate a component class.
  • Functional component Class component.
  • React elements can be user-defined components.
  • Custom components must begin with a capital letter.
  • Any input parameter of a component can be called props.
  • A component must never modify its props, either using a function declaration or through a class declaration.
  • PropTypes are used to specify whether the properties of the component strength conform to requirements and to define the props types
  • This. props represents features that, once defined, do not change, while this.state is a feature that changes as users interact.

3. State & Life Cycle

Understanding state: Think of the component as a state machine that starts with an initial state and then the user interacts, causing the state to change, leading to a rerendering of the UI.

  • The componentDidMount() method runs after the component has been rendered into the DOM
  • SetState modify state.
  • Updates to state can be asynchronous.
  • The setState method is inherited from Component.
  • SetState is an asynchronous update.

Explanation: If setState is updated every time, it means that the render function will be re-rendered frequently by the call interface. Such efficiency is very low. The best way is to get multiple updates and then do batch updates.

4. Event handling

  • React events are named in a small hump.
  • When using JSX, you pass in a function as an event handler instead of a string

5. Conditional rendering

  • &&
  • Ternary operator
  • Prevents the render method from returning NULL

6. List rendering

This.props. Children represents all the children of the component. JSX allows you to insert JavaScript variables directly into templates. If the variable is an array, all members of the array are expanded

Get the actual DOM node ref

Sometimes you need to get the real DOM node from the component, using the REF attribute

Component life cycle

  • Mounting: The real DOM is inserted
  • Updation: is being re-rendered
  • Unmounting: The real DOM has been removed

Each state provides two handlers, the will function called before entering the state and the DID function called after entering the state.

  • componentWillMount()
  • componentDidMount()
  • componentWillUpdate()
  • componentDidMount()
  • componentWillUnmount()

Mounting stage

  1. ComponentWillMount: Executed when the component is about to be loaded onto the page.
  2. Render: executes when the page state or props changes.
  3. ComponentDidMount: Executed when the component is mounted.

In the Updation stage, one is the props property change and the other is the state state change.

  1. ComponentWillUpdate, executed when the page is about to be updated.
  2. Render to perform
  3. ComponentDidUpdate, page updated after execution.

There are also two special lifecycle functions for this phase.

  • ComponentWillReceiveProps.

The child component receives props, and the function can be executed.

Unmounting The component is deleted from the page.

There are also two special state handlers

  • ComponentWillReceiveProps () : loaded component receives a new parameter called.
  • ShouldComponentUpdate (): called when the component is judged to be re-rendering.

Ajax

You can set up Ajax in the lifecycle componentDidMount() method and wait until the request succeeds to re-render the UI using the this.setState method.

Hook

  • Hooks cannot be used in class components.

The react function is special

  • The State Hook:

UseState returns two values, the current state and a function that updates it.

  • Effect Hook:

UseEffect adds the ability to manipulate side effects for componentDidMount, componentDidUpdate, and componentWillUnmount. It’s just merged into one API.

  • Context Hook :

UseContext () shared state hook.

  • Reducer Hook

useReducer

  • Hooks are named with the use prefix for easy identification. You want to use the XXX function and name the hook usexxx.

UseEffect understand

The function of Hook, solve the side effect of function components, used to introduce side effects for function components. The body of a function component should only be used to return the component’s HTML code; all other operations must be imported via hooks.

If the first useEffect argument uses a variable directly or indirectly, place it in the second useEffect argument.

Synchronization and asynchrony of setState

1. Why use setState

  • React does not implement a way to listen for data changes, like object. defineProperty in Vue2 or Proxy in Vue3
  • We must use setState to tell React that the data has changed

UseEffect (): Side effect hook

UseEffect (() => {effect // side effect return () => {cleanup // unmount, same as componentWillUnmount, do some cleanup function. }}, [input]) // dependenciesCopy the code

Effect is executed every time it is rendered.

Effect Hook is executed not only when the component is mounted, but also when the component is updated.

UseEffect can be given a second argument, which can provide an empty array, to be executed only at mount time.

UseEffect The second parameter, if changed, useEffect hook runs again. If the second argument is an empty array, the hook will not be executed on updating because it is not listening for any variables.

Sometimes, if you don’t want useEffect() to be executed every time you render, you can use its second argument, which uses an array to specify the dependencies of the side effect function and only re-render if the dependencies change.

  • React The useEffect function is called for the first rendering (componentDidMonut) and for every subsequent rendering (componentDidUpdate).
  • UseEffect defines functions that execute asynchronously without preventing the browser from updating the view, whereas the code in componentDidMonut and componentDidUpdate are executed synchronously.

UseEffect Common uses

  • Fetching Data Fetching
  • Setting up a subscription
  • Changing the DOM
  • Logging output

Context

Context allows us to pass values deep into the component tree without explicitly traversing each component.

  • Avoid layering around some props.

Some components can be passed on themselves

React Indicates the communication mode of the component

  • The parent component communicates props to the child component
  • The child component communicates with the parent component

Just pass the method to the child when the component calls, and remember to bind this here as well.

  • Communication between components across levels
  • Communication between non-nested components

Properties passed through props are read-only and can only be used, not modified.

react-transition-group

Official animation transition library. Have time to learn the API.

Note writing

React comment

 {/* Write some comments here. Comments are written in braces. * /}

Copy the code
  • JSX class name, class is className.

Redux

Brief story flow

The core concept of Redux is that components emit actions to communicate with the state manager. After the state manager receives the action, the Reducer function is used to calculate the new state, in the form of the Reducer function

(state, action) => newState
Copy the code

Dispatch action eg: OnClick, the Store will automatically call Reducer and pass in two parameters, the current state and the received action. Reducer will return a new state, and if state changes,state will call the listener. The listener gets the current state.

  1. action creators eg: onClick
  2. The store automatically calls Reducer and returns the current new state
  3. Whenever state changes, store can call the listener function to get the latest state.
  4. The component resets setState and the view is re-rendered.

The problem with using Redux alone is, where is Redux mounted, Window? , how to introduce the global picture?

Use of react-Redux,

  • A Provider is a Provider in which all children of a component can use a store.
  • Use connect connectors in each of the child components, and make a mapping with CONNECT.

Summary: React-Redux simplifies redux operations in react projects. Use the global Provider component, customize mapStateToProps, and mapDispatchToProps within the child components, and then link them together using Connect. Changes within the Reducer can be made to the point of stateless components.

Story – the chunk plug-in

For example, after dispatching an Action and before arriving at the reducer, additional operations need to be done using middleware. In practice you can use middleware to log, create crash reports, invoke asynchronous interfaces, or route.

This middleware can be enhanced with Redux-Thunk (you can use other middleware as well), which is an enhancement of Redux dispatch,

The middleware here refers to Redux’s middleware, not React’s middleware.

There is also a common plugin, React-Redux, that simplifies the Redux process.

React-Router

  • Exact matches. Only when all matches are matched, the page is displayed.
  • Get the routing object within the component using this.props. Match.
  • Redirect Label redirection, programmatic redirection.
  • Nested routines by.

Focus on router.

   <Link to='/'/>
   
   <Route path='/' component={page}>
   
Copy the code

Use of SCSS,

Sas-loader support has been added to create-react-app. After node-sass is installed, you can use it directly.

npm install node-sass --save
Copy the code

How to encapsulate a component,

  • 1. Component requirement analysis, which parameters to receive and which contents to return. You need to plan ahead, use words or charts, chances are down.
  • 2. Components are improved step by step, bit by bit, starting from the most basic place.

React HOC High-level components

High-order components are an important and complex concept in React. They are used to abstract and reuse component logic

const EnhancedComponent = higherOrderComponent(WrappedComponent);
Copy the code

High-level components can be used in the following four scenarios:

  • Manipulation of the props
  • Access component instances through ref
  • Component status upgrade
  • Wrap components with other elements

React optimizes component performance

  • Component lazy loading (React. Lazy (…)) And)
  • Pure Component
  • shouldComponentUpdate(…) {… } Life cycle functions
  • React.memo

Learning links

  • UseEffect to get the data
  • React tutorial
  • Redux Flow redux Flow