directory

  • Component description
  • Class components
  • Function component
  • Props (external data) and state (internal data) &setState
  • Complex state

I. Introduction to components

Components, conceptually similar to JavaScript functions. It takes an arbitrary input parameter (” props “) and returns a React element that describes what the page displays.

A component is an object used for composition. In programming, the role of components is to make code modular, which makes code more readable and maintainable.

In React, there are two ways to define components, function components and class components. The unwritten rules are uppercase for components and lowercase for elements

Class components

There are two ways to create a class component, the ES5 (outdated) way of writing it and the more recent ES6 way of writing it.

1. ES5 mode (out of date)

This is possible because ES5 does not support classes.

import React from 'react';
const A=React.createClass({
	render(){
		return (
			<div>Hello,world!</div>)}})export default A;
Copy the code

2. ES6

Today, we typically create class components the ES6 way.

import React from 'react';
class B extends React.Component{
	/* constructor is the initialization process */
	constructor(props){
		super(props);
	}
	render(){
		return (
			<div>Hello,world!</div>)}}export default B;
Copy the code

Function components

Functional components are good or not, but compared to class components, we face two problems. Function components have no state and lifecycle functions

No State: ReactV16.8.0 exit from Hooks API useState can be replaced.

No lifecycle: useEffect can be replaced by Hooks API that ReactV16.8.0 exits.

Some apis for simulating class components of function components

1. Creation method

// # create a function component using the arrow function
const Hello1=(props) = >{
	return (
		<div>{props.msg}</div>)}// # short for arrow function to create component
const Hello2=props= ><div>{props.msg}</div>
// # create a function
function Hello(props) {
	return (
		<div>{props.msg}</div>)}Copy the code

2. Use function components

< function name /> or function name ()

ReactDOM.render(<Hello1>,document.queryselector('root')); # or ReactDOM. Render (Hello1 (),document.queryselector('root'))
Copy the code

Props (external data) and state (internal data) &setState

1, props,

Props is external data that needs to be passed externally to a component when it is being used

The class component reads the property directly: this.props. XXX

The function component reads the parameter directly: props. XXX

  • The role of props
  1. Accept external data, can only read not write!! External data is passed by the parent component
  2. Take an external function, call that function at the appropriate time, that functionUsually a function of the parent component

  • Initialization of props in the class component

Initialization is done in constructor.

import React from 'react';
class B extends React.Component{
	constructor(props){
		super(props)
	}
	render(){}}Copy the code

Pay attention to

  1. Either no initialization, i.e., no constructor
  2. To initialize, you must write full constructor and error if you do not write super()
  3. After initialization,this.propsThat’s external dataObject addressthe
  • Initialization of props in a function component
function App(props) {
	return (
		<div>{props}</div>)}Copy the code

2. Read props data

  • Main class component A passes props data to subclass parent component B
class App extends React.Component {
	render() {
		return (
			<div>Here is the parent component<B name='Gao Yuanyuan' age='18'/>
			</div>)}}Copy the code
  • Subclass component B reads props data
import React from 'react';
class B extends React.Component{
	constructor(props){
		super(props)
	}
	render(){
		return (
			<>// Class component to read data through this.props. XXX<div>
				name:{this.props.name}
				<div>
				  age:{this.props.age}
				</div>
			  </div>
			</>)}}Copy the code

  • The function main component passes props data to the function parent
function App(props) {
	return (
		<div>Here is the function main component<Hello name='Yuan Shanshan' age='18'/>
		</div>)}Copy the code
  • The function component reads props data
import React from 'react';
const Hello=(props) = >{
	return (
		<>// The function component reads data using the parameter props<div>
			name:{props.name}
			  <div>
				age:{props.age}
			  </div>
		  </div>
		</>)}Copy the code

summary

  1. The props is external data. Only the props component can read the external data, but cannot write the data. Because this does not comply with the React specification, data can only be modified by the props data owner.
  2. To modify the props data, use a function call to modify the props data in the component that owns the props data.

State (internal data) &setState

State is internal data and represents data used within the component.

Principle of immutable data

Vue: we can say this.state.n+=1; This.setstate (this.state), however, React is not designed to manipulate data in this way, which is not in accordance with the design philosophy of React. React does not proxy-listen directly on data like Vue does. Instead of operating directly on the original data, we need to generate a new object or value

SetState is an API for modifying the value of state, which is an asynchronous operation. It is a good idea to write an arrow function in the setState() bracket to indicate the code that will operate on the data. Such as: setState (I = > I + 1)

  • Use state&setState() in class components

State needs to be added when constructor is initialized.

import React from 'react';
class B extends React.Component{
	constructor(props){
		super(props);
		this.state={
			n:0.user: {name:'frank'.age:18}}}render(){
		<>
		  <div>
			 n:{this.state.n}
			 <hr/>// N +1 is triggered, but this.state.n+=1 is not updated<button onClick={this.setState((state)= >{return {n:this.state.n+1}})}>
			+1
			</button>
		  </div>
		  <div>
		 	user:{this.state.user} 
		  </div>
		</>}}Copy the code
  • Function components use state&setState()

Use the React API: React. UseState (initialState)

The setN of n is also an asynchronous operation, producing a new object or value

React.useState Explains the portal

import React from 'react';
const App=() = >{
	const [n,setN]=React.useState(0);
	// n is the initial value of 0, setN is the operation initial value of 0 API
	return (
		<div>
		  n:{n}
		  <button onClick={()= >setN(i=>i+1)}>+1</button>
		</div>)}Copy the code

summary

  1. This. The state. The n + = 1 is invalid?The value of n has changed, but React will not trigger UI updates. The update will only be triggered by calling setState becauseReact does not proxy listen on state like Vue does.
  2. SetState is an asynchronous operation that asynchronously updates the rendered page, recommended useSetState (function)The way. The function represents operations on n, as in:setState(i=>i+1)
  3. This.setstate (this.state) not recommended? This is because the React philosophy followsImmutable dataIt doesn’t want us to modify the old state. Common code:setState({n:this.state.n+1})
  4. In the function component, passReact.useState(initialState)To simulate using state, also update the UI via setX(), also oneAsynchronous operations.

5. Complex State

What is complex state? This is when we have more than n data in our state, such as when there is both n and M or an object user. What happens when we modify only one data? You’ll notice that other data such as m will be null

This is because setState only shallow merge. It merges only the first layer of data

1. Complex state in a class component

  • Class components have n and m

In the following cases, only the value of n or m is set, and the other value is not null.

import React from 'react';
class A extends React.Component {
  constructor() {
    super(a);this.state = {
      n: 0.m: 0
    };
  }
  addN() {
    this.setState({ n: this.state.n + 1 });
    // will m be overwritten as undefined?
  }
  addM() {
    this.setState({ m: this.state.m + 1 });
    // will n be overwritten as undefined?
  }
  render() {
    return (
      <div>
         n: {this.state.n}
        <button onClick={()= > this.addN()}>n+1</button>
        m: {this.state.m}
        <button onClick={()= > this.addM()}>m+1</button>
      </div>); }}Copy the code
  • Class component has object user{}

When you have the user object below, you’ll notice that the first level properties n and m are not null, but when I just change the name in user, age is null.

Solution: Use… The object. assign operator copies the original data and then modifies it

import React from 'react';
class B extends React.Component {
  constructor() {
    super(a);this.state = {
      n: 0.m: 0.user: {
        name: "frank".age: 18}}; }addN() {
    this.setState({ n: this.state.n + 1 });
    // will m be overwritten as undefined?
  }
  addM() {
    this.setState({ m: this.state.m + 1 });
    // will n be overwritten as undefined?
  }
  changeUser() {
    this.setState({
      // m and n will not be null
      user: {
		// If age is not null =>... this.state.user;
        name: "jack"
        // age is null}}); }render() {
    return (
      <div>
        n: {this.state.n}
        <button onClick={()= > this.addN()}>n+1</button>
        m: {this.state.m}
        <button onClick={()= > this.addM()}>m+1</button>
        <hr />
        <div>user.name: {this.state.user.name}</div>
        <div>user.age: {this.state.user.age}</div>
        <button onClick={()= > this.changeUser()}>change user</button>
      </div>); }}Copy the code

2. Complex states in function components

React does not automatically merge layer 1 properties in function components.

  • Function components have n and m in them
import React from 'react';
const C = () = > {
  const [n, setN] = React.useState(0);
  const [m, setM] = React.useState(0);
  return (
    <div>
    	n:{n}
      <button onClick={()= > setN(i=>i+1)}>n+1</button>
      m:{m}
      <button onClick={()= > setM(i=>i+1)}>m+1</button>
    </div>
  );
};
Copy the code
  • The object form of a function component

If you change the value of only one object, the other data will be null.

Solution: Use… The operator copies the original data or object.assign

import React from 'react';
const D = () = > {
  const [state, setState] = React.useState({n:0.m:0});
  return (
    <div>N :{n} /* Note that this button will empty the value of m */<button onClick={()= > setState({n:state.n+1})}>n+1</button>
      m:{m}
      <button onClick={()= >setM({... state,n:state.n+1})}>m+1</button>
    </div>
  );
};
Copy the code

summary

  1. SetState in a class component automatically merges layer 1 properties, but not layer 2 and beyond.
  2. SetX in function components does not automatically merge attribute values.
  3. To solve the above problem, the attribute or value is null. We usually use. Operator or Object.assign.