1.useEffect不带第二个参数

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

例子

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

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

  // Similar to componentDidMount and componentDidUpdate:
  // 加载和state更新的时候会触发
  useEffect(() => {
    console.log(`hook-----${new Date()}`);
    console.log(`count ${count} times`);
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <Button onClick={() => setCount(count + 1)}>Click me</Button>
    </div>
  );
}

当组件第一次被加载进来的时候,控制台打印

 

当每次点击按钮'cclick me',控制台打印

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐