博客
关于我
hook钩子介绍
阅读量:305 次
发布时间:2019-03-03

本文共 778 字,大约阅读时间需要 2 分钟。

useEffect不带第二个参数

useEffect类似于React的生命周期方法,用于在组件加载和更新时执行代码。在React中,useEffect默认接受一个函数作为回调,执行时会在组件的挂载和更新时被调用。如果需要在特定条件下执行回调,可以传递依赖数组作为第二个参数。但有时候,我们并不需要依赖数组,直接传递一个函数即可。

例如:

useEffect(() => {// 更新文档标题document.title = 你点击了${count}次;});

这样写法在组件第一次加载和每次状态更新时都会被执行。

示例:

import React, { useState, useEffect } from 'react';import { Button } from '@alifd/next';

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

useEffect(() => {    console.log(`hook-----${new Date()}`);    console.log(`次数 ${count}`);    document.title = `你点击了${count}次`;});return (    

你点击了 {count} 次

);

}

第一次加载时,控制台会打印:

hook-----[当前日期时间]次数 0

每次点击按钮"Click me",控制台会打印:

hook-----[当前日期时间]次数 [当前计数值]

这个方法适用于在组件加载和更新时执行一次性操作,比如设置页面标题、执行初始数据加载等。

转载地址:http://euvm.baihongyu.com/

你可能感兴趣的文章
Pinia:$subscribe()的使用场景
查看>>
Pinpoint对Kubernetes关键业务模块进行全链路监控
查看>>
Pinterest 大规模缓存集群的架构剖析
查看>>
pintos project (2) Project 1 Thread -Mission 1 Code
查看>>
PinYin4j库的使用
查看>>
PIP
查看>>
pip install goose-extractor // SyntaxError: Missing parentheses in call to 'print'
查看>>
pip install 出现报asciii码错误的解决
查看>>
pip throws TypeError: parse() got an unexpected keyword argument ‘transport_encoding‘ 在尝试安装新软件包时
查看>>
pip 下载慢
查看>>
pip 升级报错AttributeError: ‘NoneType’ object has no attribute ‘bytes’
查看>>
pip 安装出现异常
查看>>
Pip 安装失败:需要 SSL
查看>>
Pip 安装挂起
查看>>
pip/pip3更换国内源
查看>>
pip3 install PyQt5 --user 失败
查看>>
pip3命令全解析:Python3包管理工具的详细使用指南
查看>>
pip3安装命令重复创建文件‘/tmp/pip-install-xxxxx/package‘失败
查看>>
PIPE 接口信号列表
查看>>
pipeline项目配置实战
查看>>