当前位置:网站首页>Extended hooks
Extended hooks
2022-06-26 14:31:00 【fang·up·ad】
Three common hook
Hook yes React 16.8.0 New features added , Let's use... In functional components
state
And other features
1. State Hook
(1)State Hook
Let functional components also havestate
state , Read and write status data(2) grammar :
const [xxx, setXxx] = React.useState(initValue)
initValue
Initializing values for States , Initialize the specified value for the first time and cache it internally- Return value
xxx, setXxx,
contain 2 Array of elements , They are the current status value and the status update function
(3)setXxx()
Of 2 Usage :
setXxx(newValue) The parameter is a non functional value , Directly specify the new state value , It is used internally to override the original state value
setXxx(value => newValue) Parameter is a function , Accept the original state value , Returns the new status value , It is used internally to override the original state value
Be careful ! If there are multiple states , Can only be called more than once
React.useState
, Can't use object !I'll add some 1 Case study :
import { useState } from "react"; export default function Demo(props) { const [count, setCount] = useState("0") function addOne { setCount(count + 1) # The first way to write it # setCount(count=>count+1) # The second way } return ( <div> <h2> Sum for {count}</h2> <button onClick={addOne}> I'll add some 1</button> </div> ) }
(1) Click on button , Would call addOne function , Then call the update status function , then Demo Functional components perform rendering again , This can lead to const [count, setCount] = useState("0") This code executes , Every time I click button Will let you execute this code .react The bottom layer is treated , This code will not be executed every time the update results in the re initialization of the state . Instead, keep the last status value .
(2)()=>{} Arrow function If a single parameter , Brackets can be omitted , If only one line of return value code , It can be omitted return. If the object is returned Parentheses are required ({}), Prevent and code snippets {} confusion .
2. Effect Hook
Effect Hook
Allows us to perform side effects in functional components ( Is to simulate the life cycle hook )- Side effects operation : send out Ajax request 、 Timer 、 Manually change the real DOM
Effect Hook
You can simulate three hooks :componentDidMount
、componentDidUpdate
、componentWillUnmount
React.useEffect
The first parameterreturn
The function of is equivalent tocomponentWillUnmount
, If there are more than one, they will be executed in sequence// grammar React.useEffect(() => { ... return () => { // Execute before uninstalling components , namely componentWillUnmount hook ... } }, [stateValue]) // simulation componentDidMount // The second parameter array is empty , Indicates that updates in any status are not monitored // Therefore, only the first rendering of the page will execute the output React.useEffect(() => { console.log('DidMount') return () => { console.log('WillUnmount 1') } }, []) // Simulate all States componentDidUpdate // If the second parameter is not written , Means to listen for all status updates React.useEffect(() => { console.log('All DidUpdate') return () => { console.log('WillUnmount 2') } }) // Simulate some states componentDidUpdate // The second parameter array writes the status , Indicates that only the updates of these statuses are monitored React.useEffect(() => { console.log('Part DidUpdate') return () => { console.log('WillUnmount 3') } }, [count, name]) // If called ReactDOM.unmountComponentAtNode(document.getElementById('root')) // Will be output WillUnmount 1、2、3
3. Ref Hook
Ref Hook
You can store or find labels or other data in functional components- grammar :
const refContainer = React.useRef()
- The container that holds the label object , and
React.createRef()
similar , It is also dedicated to special personnelfunction Demo() { const myRef = React.useRef() function show() { console.log(myRef.current.value) } return ( <div> <input type="text" ref={myRef} /> <button onClick={show}> Display data </button> </div> ) }
边栏推荐
- idea快捷键
- 9項規定6個嚴禁!教育部、應急管理部聯合印發《校外培訓機構消防安全管理九項規定》
- Summary of decimal point of amount and price at work and pit
- Educational Codeforces Round 117 (Rated for Div. 2)E. Messages
- Knowledge about adsorption
- 扩展-Hooks
- oracle11g数据库导入导出方法教程[通俗易懂]
- "Scoi2016" delicious problem solution
- D check type is pointer
- RISC-V 芯片架构新规范
猜你喜欢
Setup instance of layout manager login interface
Never use redis expired monitoring to implement scheduled tasks!
Gartner 2022年顶级战略技术趋势报告
Gartner 2022 Top Strategic Technology Trends Report
How to convert data in cell cell into data in matrix
Usage of unique function
How to call self written functions in MATLAB
windows版MySQL软件的安装与卸载
Matplotlib common operations
Intellij IDEA--格式化SQL文件的方法
随机推荐
启动Redis报错:Could not create Server TCP listening socket *:6379: bind: Address already in use–解决办法
Complete diagram / Euler loop
Svn commit error after deleting files locally
Why is there always a space (63 or 2048 sectors) in front of the first partition when partitioning a disk
备战数学建模32-相关性分析2
GDAL and opencv smooth and blur TIF images
[sdoi2013] forest
wptx64能卸载吗_win10自带的软件哪些可以卸载
Heap optimization dijkstra/hash table storage node number
ThreadLocal巨坑!内存泄露只是小儿科...
Hard (magnetic) disk (I)
Summary of decimal point of amount and price at work and pit
近期比较重要消息
Electron
Knowledge about adsorption
ArcGIS secondary development method - layer related operations (add, modify)
Introduction to basic knowledge of C language (Daquan) [suggestions collection]
Combat readiness mathematical modeling 31 data interpolation and curve fitting 3
Difference between classification and regression
GDAL grid data types and their type codes