Carmineprince's Blog
首页
    • HTML
    • CSS
    • JavaScript
    • Vue
    • React
    • TypeScript
    • Node
    • Flutter
    • Electron
    • Python
    • 运维
    • 重学前端
  • 分类
  • 标签
  • 归档

Ziqi Wang

胡思乱想程序员
首页
    • HTML
    • CSS
    • JavaScript
    • Vue
    • React
    • TypeScript
    • Node
    • Flutter
    • Electron
    • Python
    • 运维
    • 重学前端
  • 分类
  • 标签
  • 归档
  • 用TypeScript编写React的最佳实践
  • 项目结构搭建-慕课笔记
  • react17+ts+umi构建移动端web项目
  • CssModule同元素使用多个ClassName
  • 如何优雅的修改antd中的默认样式
  • React+Umi3的数据流解决方案-dva
  • Module "xxx" does not exist in container
  • React Hook详解
    • 一、useEffect
      • 1. 构成
      • 2. 模拟生命周期
  • React相关
carmineprince
2022-02-18

React Hook详解

# React Hook详解

# 一、useEffect

# 1. 构成

完整的useEffect

useEffect(() => {
  return () => {}
},[])
1
2
3

我们分成三个部分来看:

  1. useEffect(() => {})的箭头函数,是useEffect的effct函数,即副作用函数
  2. effect函数中的return中的箭头函数,是useEffect的返回函数,组件卸载时执行
  3. []最后一个参数,是useEffect函数的依赖项,如果useEffect依赖的数据变化,即重新执行

# 2. 模拟生命周期

# (1).模拟componentDidMount功能

useEffect的第二个参数依赖项设置为一个空数组,这样在初次调用后就不再执行了,相当于componentDidMount

function Demo () {
  useEffect(() => {
    console.log('hello world')
  }, [])
  return (
    <div>
      hello world
    </div>
  )
}
1
2
3
4
5
6
7
8
9
10

# (2).模拟componentDidMount 和 componentDidUpdate功能

当useEffect没有第二个参数的时,组件的初始化和更新都会执行

function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# (3).模拟componentDidMount 和 componentWillUnmount功能

当useEffect返回一个函数,这个函数会在组件卸载的时候执行

function Example() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    const id = setInterval(() => {
      setCount(c => c + 1);
    }, 1000);
    return () => clearInterval(id);
  }, []);

  return <h1>hello world</h1>
}
1
2
3
4
5
6
7
8
9
10
11
12
#hook
上次更新: 2/24/2022, 10:47:07 AM
Module "xxx" does not exist in container

← Module "xxx" does not exist in container

最近更新
01
pc端rem配置
03-02
02
使用动态变量ts报错的解决
02-25
03
Module "xxx" does not exist in container
02-17
更多文章>
Theme by Vdoing | Copyright © 2021-2022 Carmineprince | 鲁ICP备2021046263号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式