useState 和 useEffect

创建函数组件方式

相比类组件其实更提倡使用函数组件,因为它在很多操作上都是很便捷的,比如说没有 this。创建函数组件的方式如下:

// 箭头函数的形式
const Hello = (props) => {
  return <div>{props.message}</div>;
};
// 缩写
const Hello = (props) => <div>{props.message}</div>;
// 普通函数的形式
function Hello(props) {
  return <div>{props.message}</div>;
}

函数组件代替 class 组件

面临两个问题

  • 没有state
  • 没有生命周期

没有 state

  • React v16.8.0 推出 Hooks API
  • 其中的一个API叫做useState可以解决问题

没有生命周期

  • React v16.8.0 推出 Hooks API
  • 其中的一个API叫做useEffect可以解决问题

useEffect

  • 模拟componentDidMount 第一次渲染
useEffect(() => {
  console.log("第一次渲染");
}, []);
  • 模拟componentDidUpdate
useEffect(() => {
  console.log(" 任意属性变了");
});
useEffect(() => {
  console.log("n变了");
}, [n]);
  • 模拟componentWillUnmount
useEffect(() => {
  console.log("第一次渲染");
  return () => {
    console.log("组件要死了");
  };
});

例子:

import React, { useState, useEffect, Children } from "react";

const App = (props) => {
  const [isChildVisible, setIsChildVisible] = useState(true);
  const hide = () => {
    setIsChildVisible(false);
  };
  const show = () => {
    setIsChildVisible(true);
  };
  return (
    <>
      {isChildVisible ? (
        <button onClick={hide}>hide</button>
      ) : (
        <button onClick={show}>show</button>
      )}
      {isChildVisible ? <Child /> : null}
    </>
  );
};

const Child = (props) => {
  useEffect(() => {
    // 函数本身是在渲染的时候执行
    console.log("渲染或变化了");
    // 函数返回的函数,是在销毁的时候执行
    return () => {
      console.log("Child销毁了");
    };
  });
  return <div>Child</div>;
};

export default App;

其他生命周期怎么模拟

  • constructor 函数组件执行的时候,就相当于constructor
  • shouldComponentUpdate 后面的React.memouseMemo可以解决
  • render 函数组件的返回值就是render的返回值
comments powered by Disqus