1.React?

React was open source by the FaceBook team in May 2013. It is a JavaScript library used to build UI interfaces. It is equivalent to the V-layer framework in MVC.

React each component has a state machine concept. Components use state to maintain their own state changes. When the state changes, React virtualizes the DOM technology to increase the increment, and finally uses Diff algorithm technology to update the real native DOM efficiently.

2. The difference between Props and State?

React is a one-way, top-down data flow. React is a one-way, top-down data flow. Therefore, the understanding of prop and state should be understood from the perspective of the relationship between parent and child components:

Props: Used to transfer data between components, either parent or sibling. It is read-only, meaning that it cannot be modified, and can also be understood as data passed to the component from outside.

State: The internal state of the component (the internal data of the component, also known as component private property, cannot be accessed or modified externally). It cannot be modified directly, but the value of the state can be changed using the setState method (this method is asynchronous). Each state change causes the component to be re-rendered. No state is a stateless component, and state is a stateful component.

The parent component can be converted to props and passed to its children. The props received by the child component is read-only. To change the value, you can only change the parent component’s state.

React recommends building several stateless components to render data. Use as many stateless components as possible. Stateful components are primarily used to interact with users and services, and are ultimately passed to the stateless components through props.

React Lifecycle and lifecycle methods

The React lifecycle is divided into three phases: mount (birth), render (or update), and unmount (death). There are several interface methods for each phase, but some methods are different in Act15 and Act17, and will evolve as React versions change.

3.1React15 lifecycle method:

Constructor (): constructor(): constructor() must be super(), otherwise this will point to an error. ComponentDidMount (): The first rendering is done and the DOM is generated, which is often used for asynchronous Ajax calls. ComponentWilllUnmount (): Component unmounting and data destruction. Update phase: componentWillReceiveProps (nextProps) (the new version is invalid) : the parent component of props to render the component after the change. ShouldComponentUpdate (nextProps,nextState) : For performance optimization, control whether to rerender. ComponentWillUpdate (nextProps,nextState) (new version deprecated) : ShouldComponentUpdate returns true, the component goes to the rendering process, and goes to componentWillUpdate, where we can also get nextProps and nextState. ComponentDidUpdate (prevProps,prevState): React will only initialize componentDidmount for the first time, and update componentDidUpdate for subsequent updates. Render (): JSX of the render function generates a virtual DOM structure, compares the old and new DOM trees before and after the diff algorithm, finds the least differentiated DOM nodes and re-renders the page.Copy the code

3.2React17 lifecycle method:

Deprecated the following method for the Render phase, which could have been replaced with componentDidMount:

componentWillMount

componentWillUpdate

componentWillReceiveProps

3.2.1 Methods of Class Components:

Mount order constructor()

static getDerivedStateFromProps(props, state)   render()

componentDidMount()

Static getDerivedStateFromProps(props, State) : getDerivedStateFromProps is actually used to replace the previous function componentWillReceiveProps props to update the state of process control.

shouldComponentUpdate()

  render()

The static getSnapshotBeforeUpdate (prevProps prevState) : Instead of componentWillUpdate, this function is called before a post-update DOM update, before the most recent change is committed to the DOM element, allowing the component to get the current value before it changes.

componentDidUpdate()

Uninstall componentWillUnmount ()

3.2.2 Functional component approach

Use Estate and useEffect Hook to manage state and other features of components without writing a class.

React’s Synthetic virtual event system

4.1 Definition of events:

Event is the programming is an abstract concept, can be easy to understand for the action, an event usually by “event, the event source and listener” combined work together, a browser has the following events: keyboard, mouse events, touch events, wheel events, clipboard, user interface events, event, etc.

4.2 Event System:

React also has a custom event handling system, including event monitoring, event distribution, event callback, etc. The browser has an event system interface (we call it nativeEvent). React repackages it according to its own standard (we call it SyntheticEvent). In other words, most of the synthesized events correspond to the interface of the native event, but some different event interfaces are synthesized for compatibility. The purpose is to use React to work with different browsers, that is, to eliminate the compatibility problem between IE and W3C standard implementation.

React rewraps the event interface of the browser. Some of its events may be a composite of the interface’s original events, hence the React composite event system.

4.3 React Synthetic Event System works

For an event to work, there are two stages: event binding and event firing. Event binding: React provides an event module, event plugins for different events, and an index list of event types. React initially registers all synthesized events as global objects. When the React Diff algorithm checks that the Dom needs to be added or updated, it checks whether the prop is an event type. If so, it checks which native events depend on it based on the synthesized event type. If not registered, It registers with the current Document and executes the React callback function dispatchEvent().

React synthetic events Bind only one original event for the same type of event. React Sends event callbacks after capturing events. Event triggering: When any React event is triggered, the React dispatchEvent function is executed to execute the list of events registered and bound to this Document in batches. All event plug-ins in the corresponding plugins are executed in sequence. Each event plug-in processes its own event.

4.4 Why Is this Bound in React Event Processing?

** You must be careful with this in the JSX callback. In JavaScript, class methods do not bind this by default. If you forget to bind this.handleClick and pass it in onClick, this will be undefined when you call this function. This isn’t React specific behavior; This has to do with how JavaScript functions work. In general, if you don’t add () to the end of a method, such as onClick={this.handleclick}, you should bind this to the method. ** My understanding: **React does not automatically bind component instances of this in the latest version of React (except for life-cycle functions), so you have to manually unbind this when using event functions to tell the caller that you need to bind this to yourself. I later learn that this event belongs to your event.

4.5 How to Bind this to the React Event?

There are two options :(1) bind(this) when calling a function and (2) arrow function (that is, return a variable from the function content). I recommend method 2. Example of binding this:

export default class Life extends React.Component{ constructor(props){ super(props); this.state = { count:1 }; } render(){return (<div> <button onClick={this.handleadd} OnClick ={this.handleclick. bind(this)}> Bind this</button> <p>{this.state.count}</p> </div>) handleAdd = ()=> { console.log(this) this.setState({ count:2 }) } handleClick(){ console.log(this) this.setState({ count:3 }) } }Copy the code

5.React conditions determine the use of rendering

This piece is less cumbersome than vUE’s V-if, but may be more flexible. React conditional rendering is similar to JavaSrcipt, using JavaScript’s own if or conditional operators to create elements that represent the current state, and then letting React update the UI based on them. **if operator: if (Boolean variable) {}; The and operator &&: embed any expression in JSX by wrapping the code in curly braces. In JavaScript,true&&exession always returns expression, and false&&expression always returns false.

{unreadMessages.length > 0 &&

You have {unreadMessages.length} unread messages.

Ternary operators:

The condition operator in JavaScript? True, false.

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      The user is <b>{isLoggedIn ? 'currently' : 'not'}</b> logged in.
    </div>
  );
}
Copy the code

Prevent component rendering (i.e. hide a component) :

This is not as easy to use as VUE’s V-show, but it can sometimes be more flexible. The render method returns null instead of doing any rendering, for example:

function WarningBanner(props) { if (! props.warn) { return null; } return ( <div className="warning"> Warning! </div> ); } caller component:  render() { return ( <div> <WarningBanner warn={this.state.showWarning} /> <button onClick={this.handleToggleClick}> {this.state.showWarning ? 'Hide' : 'Show'} </button> </div> ); }}Copy the code

6.React loop rendering

React doesn’t have the V-for tag in Vue. It uses JavaScript Map() to loop, for example:

    {this.state.goods.map( good  => <li key={good.id}>{good.text}</li> )}
</ul>
Copy the code

7. Write a React component code in the basic framework

ES6 and ES7 syntax are recommended for writing the React component.

7.1 React Class Component code structure

class MyComponent extends React.Component { constructor(props) { super(props); . } state = { count: 0 } componentnentWillMount () { } componentDidMount () { } componentWillReceiveProps (nextProps) { } shouldComponentUpdate (nextProps,nextState) { } componentWillUpdate (nextProps,nextState) { } componentDidUpdate (prevProps,prevState) {} componentWillUnmount () {} // This is the object on which the function was defined. HandleChange = ()=> {this.setState({count: this.state.count + 1}); } render() {return (<div> <h2> {this.state.count}</h2> <button onClick={this.handlechange}> click </button> </div>); } } export default MyComponent;Copy the code

Main contract specifications:

  • The name of the class is the name of the component, capitalized (big hump nomenclature)
  • Class inherits from react.component
  • Class must have a render function inside, otherwise an error is reported

7.2 Function Component code structure (according to Hooks):Function Component

UseEffect (componentDidMount, componentDidUpdate, componentWillUnmount); * // Interface declaration section.... // react. FC stands for Function Component (useState,useEffect, etc.) const TableList: React.FC = () => {// useState syntax const [state, setState] = useState(initialState) UseEffect (() => {doSomething}, [input]) return (<div>.... < / div >). }; export default TableList;Copy the code

8. The React Shared State

Global sharing: umijs plugins: @umijs/plugin-initial-state with @umijs/plugin-model. Shared between multiple components: useContext hook implementation. Parent and child component sharing: state raising method, referring to the common parent component, using the parameter method.

9.React composition and inheritance usage

Instead of inheritance, the FaceBook team recommends composition, which is refining sub-components that are put together to form page components.