0%

813_hooks

import React, { Fragment } from 'react';
import root from './index';
//import ReactDOM from 'react-dom/client';
import { useState, useEffect, useRef } from 'react';
//import { unmountComponentAtNode } from 'react-dom';

export default function App() {
  const [count, setCount] = useState(0);

  const myRef = useRef();

  function add() {
    //setCount(count + 1);//第一种写法
    setCount(count => count + 1);
  }

  function unmount() {
    //版本问题不能用unmountComponentAtNode
    root.unmount(document.querySelector('#root'));
  }

  function show() {
    alert(myRef.current.value);
  }

  useEffect(() => {
    let timer = setInterval(() => {
      setCount(count => count + 1);
    }, 1000);

    //组件卸载前执行,这里返回的函数相当于componentWiiUnmount
    return () => {
      clearInterval(timer);
    };
  }, [count]);

  return (
    // Fragment能且只能接收key参数
    <Fragment key={1}>
      <input type="text" ref={myRef} />
      <h1>我被点击了{count}</h1>
      <button onClick={add}>点我</button>
      <button onClick={unmount}>卸载组件</button>
      <button onClick={show}>点我提示数据</button>
    </Fragment>
  );
}