React中常见的hook

49 阅读1分钟

1 useState


// 用于初始化以及修改数据
import React from 'react' 

export default function UseState() {
  const [count, setCount] = React.useState(0)
  const [name, setName] = React.useState('tom')
  function add() {
    // setCount(count+1)
    setCount(count => {
        return count+2
    })
  }
  function changeName() {
   setName('jerry')
  }
  return (
    <div>
       <h1>当前求和为: {count}</h1>
       <h1>我的名字是: {name}</h1>
       <button onClick={add}>点我+1</button>
       <button onClick={changeName}>点我改名</button>
    </div>
  )
}

2 useEffect

// 相当于componentDidMount,componentDidUpdate,componentWillUnmount 的组合
// 如果不加第二个参数,相当于componentDidMount,componentDidUpdate的组合;
// 如果第二个参数为[],相当于componentDidMount,
// 在第一个参数中return的函数,相当于componentWillUnmount
// React中的副作用操作:发ajax请求,设置定时器,手动更改真实DOM

  React.useEffect(() => {
      console.log('componentDidMount---componentDidUpdate')
  })
  
 React.useEffect(() => {
      console.log('相当于componentDidMount,可以开启定时器')
      let timer = setInterval(() => {
        setCount(count => count+3)
      }, 3000) 
      return () => {
          console.log('相当于componentWillUnmount')
          clearInterval(timer)
      }
  }, [])

3 useRef

const inputRef = React.useRef() // step1
  const alertInputValue = () => {
      alert(inputRef.current.value)  // step3
  }
  return (
    <div>
       <input ref={inputRef}/>  {/* step2 */}
       <button onClick={alertInputValue}>点我输出当前输入框的值</button>
    </div>
  )

对比vue中

<template>
  <div ref="box">box</div> // step2
</template>

    const box = ref(null); // step1
    const getDom = () => {
      console.log(box.value) // step3
    };
    
    onMounted(() => {
      getDom();
    });