博客
关于我
hook钩子介绍
阅读量:304 次
发布时间: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/

你可能感兴趣的文章
NI笔试——大数加法
查看>>
NLP 基于kashgari和BERT实现中文命名实体识别(NER)
查看>>
Nmap扫描教程之Nmap基础知识
查看>>
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>
No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
查看>>
NO.23 ZenTaoPHP目录结构
查看>>
NoClassDefFoundError: org/springframework/boot/context/properties/ConfigurationBeanFactoryMetadata
查看>>
Node JS: < 一> 初识Node JS
查看>>