当前位置:网站首页>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 have  state  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 :componentDidMountcomponentDidUpdatecomponentWillUnmount
  • React.useEffect  The first parameter  return  The function of is equivalent to  componentWillUnmount , 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 personnel
function 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>
  )
}
原网站

版权声明
本文为[fang·up·ad]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206261329279133.html