React hook特性

95 阅读1分钟

hook

Hook 是 React 16.8 的新增特性。它可以让你在不编写 class 的情况下使用 state 以及其他的 React 特性。

useState 组件状态

// rfc 函数组件快捷方式
// react16.8版本后hook特性 函数组件使用 useState
// useState 函数组件使用state
// 1.引入useState
import React,{useState} from 'react'

export default function App() {
  // 2. useState state 和setState方法
  // 参数1 state的名称 参数2 修改state的方法 参数3 state的默认值
  // 想当于rcc 中 state = {num:1}
  const [num, setNum] = useState(1)
  // 声明定义一个state
  const [count, setCount] = useState(100)
  // 练习 state 存储count值默认100 每次点击按钮+10
  return (
    <div>
      {num}
      <button onClick={()=>setNum(num+1)}>{num}</button>
      <button onClick={()=>setCount(count+10)}>{count}</button>
    </div>
  )
}

生命周期useEffect

// 函数组件hook特性,提供函数组件生命周期使用
// useEffect
// 1.导入useEffect
import React, { useEffect, useState } from "react";

export default function App() {
  // useState
  const [show, setShow] = useState(false);
  return (
    <div>
      父组件
      {/* 调用子组件 */}
      <button onClick={() => setShow(!show)}>显示/隐藏</button>
      {show ? <Son /> : null}
    </div>
  );
}
function Son() {
  const [num, setNum] = useState(1);
  // 练习 监控count值的变化
  // 更新前和更新后值变化
  const [count, setCount] = useState(100);
  // 第一段 挂载或者更新
  // 第二段 将要卸载
  // 第三段 监控数据变化
  useEffect(() => {
    // componentDidMount和componentDidUpdate结合
    // console.log("挂载和刷新触发了");
    // 更新后的数据
    console.log("num更新后:", num);
    // console.log("count更新后:", count);
    return () => {
      // componentWillMount 将要卸载触发
      // console.log("将要卸载触发了");
      console.log("num更新前:", num);
      // console.log("count更新前:", count);
    };
    // [input] 监控组件状态的变化 没有监控的值,就写[]
  }, [num]);
  useEffect(() => {
    console.log("count更新后:", count);
    return () => {
      console.log("count更新前:", count);
    };
  }, [count]);
  return (
    <div style={{ border: "2px solid green" }}>
      <div>这是子组件</div>
      <button onClick={() => setNum(num + 1)}>{num}</button>
      <br />
      <button onClick={() => setCount(count + 10)}>{count}</button>
    </div>
  );
}