current position:Home>Summary of react learning (2)
Summary of react learning (2)
2022-01-26 23:53:00 【APythonC】
be-all Tips All of them are me OneNote Notes in , The copy is the picture , Too lazy to turn the text
Chapter two :React Component-oriented programming
One 、 Basic understanding and use
1.1 Use React Developer tools debugging
1.2 Functional component
//1. Create functional components
function MyComponent(){
console.log(this); // Here this yes undefined, because babel Strict mode is turned on after compilation
return <h2> I'm a component defined by a function ( Apply to 【 Simple components 】 The definition of )</h2>
}
//2. Render component to page
ReactDOM.render(<MyComponent/>,document.getElementById('test'))
Yes ReactDOM.render() after , What happened? ?
- React Parsing component Tags , eureka MyComponent Components
- Discover that components are defined using functions , The function is then called. , The virtual machine that will be returned DOM Turn to reality DOM, Then it appears on the page
1.3 Class components
//1. Create a class component
class MyComponent extends React.Component {
render(){
// Methods defined in class , They are all placed on the prototype object of the class , For instance
//render Where did you put it ?—— MyComponent On the prototype object , For example .
//render Medium this Who is it? ?—— MyComponent Instance object of <=> MyComponent Component instance object .
console.log('render Medium this:',this);
return <h2> I'm a component defined by a class ( Apply to 【 Complex components 】 The definition of )</h2>
}
}
//2. Render component to page
ReactDOM.render(<MyComponent/>,document.getElementById('test'))
Yes ReactDOM.render() after , What happened? ?
- React Parsing component Tags , eureka MyComponent Components
- Discovery components are defined using classes , And then new Come up with an instance of this class , And call the render Method
- take render Back to the virtual DOM Turn to reality DOM, Then it appears on the page
1.4 Pay attention to the point
- Component names must be capitalized
- fictitious DOM Element can only have one root element
- fictitious DOM Element must have an end tag
- Methods defined in class , They are all placed on the prototype object of the class , For instance
- By default, methods in the class turn on local strict mode , therefore this Pointing to undefined
1.5 The basic process of rendering class component labels
- React Internally, component instance objects are created
- call render() Get virtual DOM , And it's true DOM
- Insert inside the specified page element
Two 、 Three core attributes of component instances 1 —— state
2.1 for instance
//1. Create components
class Weather extends React.Component{
// Initialization status
state = {
isHot:false,wind:' breeze '}
render(){
// Deconstruct assignment to get state
const {
isHot,wind} = this.state
return <h1 onClick={
this.changeWeather}> It's very... Today {
isHot ? ' scorching hot ' : ' cool '},{
wind}</h1>
}
// Custom method ———— In the form of an assignment statement + Arrow function
changeWeather = () => {
const isHot = this.state.isHot
this.setState({
isHot:!isHot})
}
}
//2. Render component to page
ReactDOM.render(<Weather/>,document.getElementById('test'))
2.2 understand state
- state Is the most important property of a component object , Value is the object ( It can contain more than one key-value The combination of )
- Components are called " State machine ", You can't modify or update state To update the corresponding page display ( Rerender component )
2.3 Pay close attention to
- In the component render Methods this You can't modify or update
- You can't modify or update this by undefined, How to solve ?
(1) Force binding this: You can't modify or update bind()
(2) Arrow function ( In the arrow function this Point to the outer layer , Point here to Weather) - Status data , You can't modify or update
- Pay serious attention to : The state must pass through setState updated , And update is a kind of merge , It's not a replacement
- This is the wrong way to write :this.state.isHot = !isHot
3、 ... and 、 Three core attributes of component instances 2 —— props
Functional components don't have state and resf attribute , Only props
3.1 for instance
// Create components
class Person extends React.Component{
constructor(props){
// Whether the constructor receives props, Whether to pass to super, Depending on : Whether you want to pass... In the constructor this visit props
// General constructors can omit
super(props)
console.log('constructor',this.props);
}
// Type tag properties 、 The limits of necessity
static propTypes = {
name:PropTypes.string.isRequired, // Limit name Will pass , And is a string
sex:PropTypes.string,// Limit sex For the string
age:PropTypes.number,// Limit age Is the value
}
// Specifies the default label attribute value
static defaultProps = {
sex:' male ',//sex The default value is male
age:18 //age The default value is 18
}
render(){
const {
name,age,sex} = this.props
//props Is read-only
//this.props.name = 'jack' // This line of code will report an error , because props Is read-only
return (
<ul>
<li> full name :{
name}</li>
<li> Gender :{
sex}</li>
<li> Age :{
age+1}</li>
</ul>
)
}
}
// Render component to page
ReactDOM.render(<Person name="jerry"/>,document.getElementById('test1'))
// {...p} For batch delivery props, Also known as batch transfer tag attribute , The expansion operator cannot expand an object , But introduce react file , Write babel Code , You can use the expand operator to expand
// const p = {name:' Lao Liu ',age:18,sex:' Woman '}
// ReactDOM.render(<Person {...p}/>,document.getElementById('test3'))
3.2 understand props
- Every component object will have props(properties Abbreviation ) attribute
- All properties of the component tag are stored in props in
3.3 effect
- Pass the changed data from the outside to the inside of the component through the tag attribute
- Be careful : Do not modify inside the component props data
3.4 Function components use props
// Create components
function Person (props){
const {
name,age,sex} = props
return (
<ul>
<li> full name :{
name}</li>
<li> Gender :{
sex}</li>
<li> Age :{
age}</li>
</ul>
)
}
Person.propTypes = {
name:PropTypes.string.isRequired, // Limit name Will pass , And is a string
sex:PropTypes.string,// Limit sex For the string
age:PropTypes.number,// Limit age Is the value
}
// Specifies the default label attribute value
Person.defaultProps = {
sex:' male ',//sex The default value is male
age:18 //age The default value is 18
}
// Render component to page
ReactDOM.render(<Person name="jerry"/>,document.getElementById('test1'))
Four 、 Three core attributes of component instances 3 —— refs
4.1 for instance
// Create components
class Demo extends React.Component{
// Display the data in the left input box
// In string form ref
showData = ()=>{
const {
input1} = this.refs
alert(input1.value)
}
// Display the data in the input box on the right
// In the form of callbacks ref
showData2 = ()=>{
const {
input2} = this
alert(input2.value)
}
render(){
return(
<div>
<input ref="input1" type="text" placeholder=" Click the button to prompt data "/>
<button onClick={
this.showData}> Click the data on the left of my prompt </button>
<input ref={
c => this.input2 = c } onBlur={
this.showData2} type="text" placeholder=" Lost focus prompt data "/>
</div>
)
}
}
// Render component to page
ReactDOM.render(<Demo/>,document.getElementById('test'))
4.2 understand refs
Tags within components can define ref Attribute to identify yourself
4.3 code
- In string form ref
<input ref="input1"/>
- In the form of callbacks ref
// Place the current node on the component instance itself , And named him input1
// c yes currentNode It means
<input ref = c => this.input1 = c />
- createRef establish ref Containers
// React.createRef After calling, you can return a container , The container can be used to store ref The identified node , The container is “ Specially assigned person ” Of
class Demo extends React.Component{
// With a few, you have to create a few
myRef = React.createRef()
myRef2 = React.createRef()
// Display the data in the left input box
showData = ()=>{
// current It's inside the container key
alert(this.myRef.current.value);
}
// Display the data in the input box on the right
showData2 = ()=>{
alert(this.myRef2.current.value);
}
render(){
return(
<div>
<input ref={
this.myRef} type="text" placeholder=" Click the button to prompt data "/>
<button onClick={
this.showData}> Click the data on the left of my prompt </button>
<input onBlur={
this.showData2} ref={
this.myRef2} type="text" placeholder=" Lost focus prompt data "/>
</div>
)
}
}
// Render component to page
ReactDOM.render(<Demo/>,document.getElementById('test'))
4.4 Pay attention to the point
- The callback function in the form of inline is no different from that in the form of class binding , Inline will be called more than once when updating , It can be used directly
- In string form ref The efficiency is not high
- createRef Creating containers is cumbersome , With one, you have to create one , So use less
5、 ... and 、 Event handling
- adopt onXxx Property to specify the event handler ( Pay attention to case )
(1)React Using custom ( synthesis ) event , Instead of using native DOM event —————— For better compatibility
(2)React Events in are handled through event delegation ( Delegate to the outermost element of a component ) ———————— For efficiency - adopt event.target Get information about what happened DOM Element object —————————— Don't overuse ref
showData2 = (event)=>{
alert(event.target.value);
}
6、 ... and 、 Collect form data
6.1 Controlled components
characteristic : Save the input into the status (state), Take it again when you need it ( It can be omitted ref)
// Create components
class Login extends React.Component{
// Initialization status
state = {
username:'', // user name
password:'' // password
}
// Save user name to status
saveUsername = (event)=>{
this.setState({
username:event.target.value})
}
// Save password to status
savePassword = (event)=>{
this.setState({
password:event.target.value})
}
// Callback for form submission
handleSubmit = (event)=>{
event.preventDefault() // Block form submission
const {
username,password} = this.state
alert(` The user name you entered is :${
username}, The password you entered is :${
password}`)
}
render(){
return(
<form onSubmit={
this.handleSubmit}>
user name :<input onChange={
this.saveUsername} type="text" name="username"/>
password :<input onChange={
this.savePassword} type="password" name="password"/>
<button> Sign in </button>
</form>
)
}
}
// Rendering Components
ReactDOM.render(<Login/>,document.getElementById('test'))
6.2 Uncontrolled components
characteristic : Enter the cash in and cash out
// Create components
class Login extends React.Component{
handleSubmit = (event)=>{
event.preventDefault() // Block form submission
const {
username,password} = this
alert(` The user name you entered is :${
username.value}, The password you entered is :${
password.value}`)
}
render(){
return(
<form onSubmit={
this.handleSubmit}>
user name :<input ref={
c => this.username = c} type="text" name="username"/>
password :<input ref={
c => this.password = c} type="password" name="password"/>
<button> Sign in </button>
</form>
)
}
}
// Rendering Components
ReactDOM.render(<Login/>,document.getElementById('test'))
7、 ... and 、 Higher order function —— The function is coriolized
Higher order function : If a function conforms to the following 2 Any one of the specifications , Then the function is a higher-order function
- if A function , The received parameter is a function , that A It's called a higher-order function
- if A function , The return value of the call is still a function , that A It's called a higher-order function
Common higher-order functions are :Promise、setTimeout、arr.map() wait
The coriolisation of functions : adopt The function call continues to return the function The way , Realize the function coding form of multiple received parameters and finally unified processing
function sum(a){
return(b)=>{
return (c)=>{
return a+b+c
}
}
}
Take the above collection form data as an example :
// Save form data to state
// according to data Type of return event.target.value
saveFormData = (dataType)=>{
return (event)=>{
this.setState({
[dataType]:event.target.value})
}
}
// Don't use Curry's writing
saveFormData = (dataType,event)=>{
this.setState({
[dataType]:event.target.value})
}
8、 ... and 、 Life cycle of components
8.1 Understand life cycle
- A component goes through some specific stages from creation to death
- React The component contains a series of hook functions ( Life cycle callback function , It can be understood as hooking out this function when necessary ), Will call... At a specific time ( Life cycle callback function <=> Life cycle hook function <=> Life cycle function <=> Lifecycle hook )
- When we define components , In a specific lifecycle callback function , Do a specific job
8.2 Life cycle flowchart ( used )

Three stages of the life cycle ( used )
-
Initialization phase : from ReactDOM.render() Trigger — First rendering
1.constructor(): Constructors
2.componentWillMount(): The hook on which the component will be mounted
3.render(): One that must be used
4.componentDidMount(): Hook after component mounting , Usually do some initialization in this hook , for example : Turn on timer 、 Send network request 、 Subscribe to news -
Update phase : From within the component this.setSate() Or the parent component restarts render Trigger
1.shouldComponentUpdate(): Controls the of component updates “ valve ”, The return value is true I'm going to continue ,false Then directly interrupt , If you don't write , The default return value of the bottom layer is true2.componentWillUpdate(): The hook that the component will update
3.render()
4.componentDidUpdate(): Hook after component update -
Uninstall components : from ReactDOM.unmountComponentAtNode() Trigger
1.componentWillUnmount(): The hook that the component will unload , Usually do some finishing work in this hook , for example : off timer 、 Unsubscribe from messages
8.3 Life cycle ( used ) give an example
// Create components
class Count extends React.Component{
// Constructors
constructor(props){
console.log('Count---constructor');
super(props)
// Initialization status
this.state = {
count:0}
}
// Add 1 Button callback
add = ()=>{
// Get the original state
const {
count} = this.state
// Update status
this.setState({
count:count+1})
}
// Callback of unload component button
death = ()=>{
ReactDOM.unmountComponentAtNode(document.getElementById('test'))
}
// Force the callback of the update button
force = ()=>{
this.forceUpdate()
}
// The hook on which the component will be mounted
componentWillMount(){
console.log('Count---componentWillMount');
}
// Hook after component mounting
componentDidMount(){
console.log('Count---componentDidMount');
}
// The hook that the component will unload
componentWillUnmount(){
console.log('Count---componentWillUnmount');
}
// Controls the of component updates “ valve ”
shouldComponentUpdate(){
console.log('Count---shouldComponentUpdate');
return true
}
// The hook that the component will update
componentWillUpdate(){
console.log('Count---componentWillUpdate');
}
// Hook after component update
componentDidUpdate(){
console.log('Count---componentDidUpdate');
}
render(){
console.log('Count---render');
const {
count} = this.state
return(
<div>
<h2> The current sum is :{
count}</h2>
<button onClick={
this.add}> Am I +1</button>
<button onClick={
this.death}> Uninstall components </button>
<button onClick={
this.force}> Do not change the data in any state , Forced update </button>
</div>
)
}
}
8.4 Life cycle flowchart ( new )

The difference between old and new life cycles :
- Abolish the three hooks of the old life cycle : componentWillMount、 componentWillReceiveProps and
componentWillUpdata - Two new hooks : getDerivedStateFromProps and getSnapshotBeforeUpdate
1.getDerivedStateFromProps: from props Get derived from state, namely state Value depends at all times props
2.getSnapshotBeforeUpdate: Take a snapshot before updating the component , The return value can be of any type
8.5 Important hooks
- render: Initialize rendering or update rendering calls
- componentDidMount: Turn on monitoring , send out ajax request
- componentWillUnmount: Do some finishing work , Such as : Clear timer
8.6 A hook about to be discarded
- componentWillMount
- componentWillReceiveProps
- componentWillUpdate
These hooks have will, A warning will appear now , The next big version needs to add UNSAFE_ Prefix can be used , It may be completely abandoned in the future , Not recommended
Nine 、 fictitious DOM And DOM Diffing Algorithm
9.1 Basic schematic diagram
9.2 Add :key The role of
Classic interview questions :
- react/vue Medium key What's the role ?(key What is the internal principle of ?)
- Why when traversing a list ,key It's better not to use it index?
1. fictitious DOM in key The role of :
(1) To put it simply : key Is a virtual DOM Identification of the object , When updating the display key Plays an extremely important role
(2) Say in detail : When the data in the state changes ,react Will be based on 【 The new data 】 Generate 【 New virtual DOM】, And then React Conduct 【 New virtual DOM】 And 【 Old virtual DOM】 Of diff Compare , The comparison rules are as follows :
a. Old virtual DOM Found with the new virtual DOM same key:
a1. If virtual DOM The content in the has not changed , Directly use the previous reality DOM
a2. If virtual DOM The content has changed , Then a new reality is generated DOM, Then replace the previous real... In the page DOM
b. Old virtual DOM The new virtual machine was not found in DOM same key:
Create a new reality based on the data DOM, Then render to the page
2. use index As key Problems that may arise :
(1) If the data is : Add in reverse order 、 Reverse order deletion and other destructive operations :
It creates unnecessary reality DOM to update ==> The interface effect is OK , But low efficiency
(2) If the structure also contains... Of the input class DOM:
There will be mistakes DOM to update ==> There is a problem with the interface
(3) Be careful ! If there is no reverse order addition to the data 、 Reverse order deletion and other destructive operations , For rendering only, the list is used to show , Use index As key There is no problem
3. How to choose key:
(1) It is best to use the unique identification of each data as key, such as id、 cell-phone number 、 ID number 、 Unique value such as student number
(2) If you're sure it's just a simple display of data , use index It's OK, too
React Series summary :
copyright notice
author[APythonC],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262352576528.html
The sidebar is recommended
- Spring IOC container loading process
- [thinking] the difference between singleton mode and static method - object-oriented programming
- Hadoop environment setup (MySQL environment configuration)
- 10 minutes, using node JS creates a real-time early warning system for bad weather!
- Git tool
- Force deduction algorithm - 92 Reverse linked list II
- What is the sub problem of dynamic programming?
- C / C + +: static keyword summary
- Idea does not have the artifacts option when configuring Tomcat
- Anaconda can't open it
guess what you like
-
I don't know how to start this
-
Matlab simulation of transportation optimization algorithm based on PSO
-
MySQL slow log optimization
-
[Vue] as the window is stretched (larger, smaller, wider and higher), the text will not be displayed
-
Popular Linux distributions for embedded computing
-
Suzhou computer research
-
After installing SSL Certificate in Windows + tomcat, the domain name request is not successful. Please answer!!
-
Implementation time output and greetings of jQuery instance
-
The 72 year old uncle became popular. Wu Jing and Guo fan made his story into a film, which made countless dreamers blush
-
How to save computer research
Random recommended
- Springboot implements excel import and export, which is easy to use, and poi can be thrown away
- The final examination subjects of a class are mathematical programming, and the scores are sorted and output from high to low
- Two pronged approach, Tsinghua Professor Pro code JDK and hotspot source code notes, one-time learning to understand
- C + + recursive knapsack problem
- The use of GIT and GitHub and the latest git tutorial are easy to understand -- Video notes of crazy God speaking
- PostgreSQL statement query
- Ignition database test
- Context didn't understand why he got a high salary?, Nginxfair principle
- Bootstrap switch switch control user's guide, springcloud actual combat video
- A list that contains only strings. What other search methods can be used except sequential search
- [matlab path planning] multi ant colony algorithm grid map path planning [including GUI source code 650]
- [matlab path planning] improved genetic algorithm grid map path planning [including source code phase 525]
- Iinternet network path management system
- Appium settings app is not running after 5000ms
- Reactnative foundation - 07 (background image, status bar, statusbar)
- Reactnative foundation - 04 (custom rpx)
- If you want an embedded database (H2, hsql or Derby), please put it on the classpath
- When using stm32g070 Hal library, if you want to write to flash, you must perform an erase. If you don't let it, you can't write continuously.
- Linux checks where the software is installed and what files are installed
- SQL statement fuzzy query and time interval filtering
- 69. Sqrt (x) (c + + problem solving version with vs runnable source program)
- Fresh students are about to graduate. Do you choose Java development or big data?
- Java project: OA management system (java + SSM + bootstrap + MySQL + JSP)
- Titanic passenger survival prediction
- Vectorization of deep learning formula
- Configuration and use of private image warehouse of microservice architect docker
- Relearn JavaScript events
- For someone, delete return 1 and return 0
- How does Java dynamically obtain what type of data is passed? It is used to judge whether the data is the same, dynamic data type
- How does the database cow optimize SQL?
- [data structure] chain structure of binary tree (pre order traversal) (middle order traversal) (post order traversal) (sequence traversal)
- Webpack packaging optimization solution
- 5. Operation element
- Detailed explanation of red and black trees
- redhat7. 9 install database 19C
- Blue Bridge Cup notes: (the given elements are not repeated) complete arrangement (arrangement cannot be repeated, arrangement can be repeated)
- Detailed explanation of springboot default package scanning mechanism and @ componentscan specified scanning path
- How to solve the run-time exception of test times
- Detailed explanation of k8s management tool kubectl
- Android system view memory command