Simple component – JSX
class HelloMessage extends React.Component {
render() {
return (
<div>
Hello {this.props.name}
</div>
);
}
}
ReactDOM.render(
<HelloMessage name="Taylor" />.document.getElementById('hello-example'));Copy the code
Stateful component – JSX
Using external data (accessed through this.props), the component can also maintain its internal state data (accessed through this.state). When the component’s state data changes, the component calls the Render () method again to rerender the corresponding markup. Note: the setState interface has one function as synchronous and accepts other types of parameters as asynchronous
class Timer extends React.Component {
constructor(props) {
super(props);
this.state = { seconds: 0 };
}
tick() {
this.setState(state= > ({
seconds: state.seconds + 1
}));
}
componentDidMount() {
this.interval = setInterval(() = > this.tick(), 1000);
}
render() {
return (
<div>
Seconds: {this.state.seconds}
</div>
);
}
}
ReactDOM.render(
<Timer />.document.getElementById('timer-example'));Copy the code
Function components (stateless)
The output is predictable
function Square(props) {
return (
<button className="square" onClick={props.onClick}>
{props.value}
</button>
);
}
Copy the code
Summary of several points: as follows, please refute:
The first is the difference between object-oriented and functional programming, two different sets of design ideas. (Function components more closely match the React framework design philosophy)
The React component itself is positioned as a function, a function that eats data and spit out the UI. The React framework’s main job is to convert declarative code into imperative DOM operations in a timely manner, mapping data-level descriptions to user-visible UI changes. This means that, in principle, React data should always be tightly bound to render, whereas class components can’t.
Second: “function components will capture the inside of the render state, this is the biggest difference between two types of components” demo: codesandbox. IO/s/pjqnl16lm…
Although the props themselves are immutable, this is mutable, and the data on this can be modified
Hook is a new feature in React 16.8. It lets you use state and other React features without having to write a class
Essence of Hooks: A set of “Hooks” that make functional components more powerful and flexible
UseState: Sets the initial value.
One problem: If the next state depends on the new value of the previous state. How to deal with it?
import React, { useState, useEffect } from "react";
export default function Counter() {
const [count, setState] = useState(1);
const [count2, setState2] = useState(1);
useEffect(() => {});
return (
<>
Count: {count} {count2}
<button onClick={() => setState(1)}>Reset</button>
<button
onClick={() => {
setState(count - 1);
setState2(count);
}}
>
-
</button>
<button
onClick={() => {
setState(count + 1);
setState2(count);
}}
>
+
</button>
</>
);
}
Copy the code
UseEffect: Effect will be executed at the end of each rendering round, but you can choose to have it executed only when certain values change. Almost 90% of the time, you should use this. This is after render, your callback is executed, but it doesn’t block Browser painting, sort of asynchronous, but class’s componentDidMount Synced with componentDidUpdate, run after render,useEffect performs better than class in most scenarios.
UseEffect (()=>{return ()=>{// Resources such as subscriptions or timer ids created by Effect need to be cleared when the component is uninstalled. To do this, useEffect returns a cleanup function}},[])Copy the code
useEffect(() => { const subscription = props.source.subscribe(); Return () => {// Clear subscription subscription. Unsubscribe (); };Copy the code
UseLayoutEffect: This is used when working with the DOM. You need to use this when your useEffect operation needs to work with the DOM and change the style of the page. Otherwise, you may have flash screen problems. The callback function in useLayoutEffect executes immediately after the DOM update is complete, but runs before the browser can do any drawing, blocking the browser’s drawing.
UseRef: get component instance object or DOM object, map, shallow copy, ‘.current ‘, listen on a node in DOM.
Forwardref () {props,res} -ref,useRef. The child component receives the parent ref node
UseImperativeHandle: Determines the methods and attributes accepted by the REF component
UseContext: Allows you to read the value of the context and subscribe to changes in the context. Use < myContext. Provider> in the upper component tree to provide the context for the lower component and create a public creteContext outside the component. Components share state
UseHook: To define a custom hook, add the use keyword in front of the function
Performance optimization:
UseReducer: similar to redux-Reducer, it is used to deal with complex state logic and contains multiple subvalues. It is an alternative to Usestate. Using useReduser also makes shallow rendering for performance optimization for components that trigger deep updates
import React, { useReducer } from "react";
function init(initialCount) {
return { count: initialCount, count2: initialCount };
}
function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + 1, count2: state.count + 1 };
case "decrement":
return { count: state.count - 1, count2: state.count + 1 };
case "reset":
return init(action.payload);
default:
throw new Error();
}
}
export default function Counter({ initialCount }) {
const [state, dispatch] = useReducer(reducer, 1, init);
return (
<>
Count: {state.count} {state.count2}
<button
onClick={() => dispatch({ type: "reset", payload: initialCount })}
>
Reset
</button>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
</>
);
}
Copy the code
UseMemo: Sets the dependency array. Only when the dependency array changes will the parameter function be executed, to solve the repeated rendering, to solve the performance optimization
UseCallback: used to cache functions
The React team has two react-hooks guidelines for developers, which are as follows:
Only call Hook in React function;
Do not call hooks in loops, conditions, or nested functions.
import React, { useState } from "react"; IsMounted = false; // isMounted = false; Function PersonalInfoComponent() {// Define variable logic unchanged let name, age, career, setName, setCareer; // This is a debug operation console.log("isMounted is", isMounted); // Append if logic here: only when rendering for the first time (the component is not yet mounted) will the name and age states be fetched if (! IsMounted) {// eslint-disable-next-line [name, setName] = useState("修 修 "); // eslint-disable-next-line [name, setName] = useState("修 修 "); // eslint-disable-next-line [age] = useState("99"); // Set isMounted to true after the internal logic is executed once. } // The logic for career information remains unchanged [career, setCareer] = useState(" I am a front-end, love to eat bear biscuits "); // Append the output to career, which is also a debug operation console.log("career", career); Return (<div className="personalInfo"> {name? <p> name: {name}</p> : null} {age? < p > age: {age} < / p > : null} < p > career: {career} < / p > < button onClick = {() = > {elegantly-named setName (" show shes "); </button> </div>); } export default PersonalInfoComponent;Copy the code
Hooks, at the bottom, rely on sequential linked lists for proper functioning