useEffect使用的介绍

  • Post author:
  • Post category:其他


如果你熟悉 React class 的生命周期函数,你可以把 useEffect Hook 看做 componentDidMount,componentDidUpdate 和 componentWillUnmount 这三个函数的组合。

使用一个 componentDidMount 的功能

function Demo () {
  useEffect(() => {
    console.log('hello world')
  }, [])
  return (
    <div>
      hello world
    </div>
  )
}
// 等价于
class Demo extends Component {
  componentDidMount() {
    console.log('hello world')
  }
  render() {
    return (
      <div>
        hello world
      </div>
    );
  }
}

使用组合 componentDidMount componentDidUpdate 的功能

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  componentDidMount() {
    document.title = `You clicked ${this.state.count} times`;
  }

  componentDidUpdate() {
    document.title = `You clicked ${this.state.count} times`;
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Click me
        </button>
      </div>
    );
  }
}
// 等价于
import React, { useState, useEffect } from 'react';

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>
  );
}


使用组合 componentDidMount componentWillUnmount 的功能

class Example extends Component {
  constructor (props) {
    super(props);
    this.state = {
      count: 0
    }
  }
  componentDidMount() {
    this.id = setInterval(() => {
      this.setState({count: this.state.count + 1})
    }, 1000);
  }
  componentWillUnmount() {
    clearInterval(this.id)
  }
  render() { 
    return <h1>{this.state.count}</h1>;
  }
}
// 等价于
function Example() {
  const [count, setCount] = useState(0);

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

  return <h1>hello world</h1>
}


使用一个 componentDidUpdate 的功能

class Example extends Component {
  constructor (props) {
    super(props);
    this.state = {count: 0}
  }
  componentDidUpdate(prevProps, prevState) {
    console.log(this.state.count, '更新时候的数据')
  }
  handleClick = () => {
    this.setState({count: this.state.count+1})
  }
  render() {
    return (
      <div>
        <div>{this.state.count}</div>
        <button onClick={this.handleClick}>+</button>
      </div>
    );
  }
}
// 等价于
function Example () {
  const [count, setCount] = useState(0);

  const prevCountRef = useRef(false);
  useEffect(() => {
    if (prevCountRef.current) {
      console.log('更新时候的数据')
    } else {
      prevCountRef.current = true
    }
  });

  return (
    <div>
      <div>{count}</div>
      <button onClick={() => {setCount(count+1)}}>+</button>
    </div>
  )
}


useEffect

如果你熟悉 React class 的生命周期函数,你可以把 useEffect Hook 看做 componentDidMount,componentDidUpdate 和 componentWillUnmount 这三个函数的组合。

默认情况下,它在第一次渲染之后和每次更新之后都会执行。(我们稍后会谈到如何控制它。)你可能会更容易接受 effect 发生在“渲染之后”这种概念,不用再去考虑“挂载”还是“更新”。React 保证了每次运行 effect 的同时,DOM 都已经更新完毕。

将 document 的 title 设置为点击次数

import React, { useState, useEffect } from 'react';

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

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

  return (
    <div>
      <p>次数:{count}</p>
      <button onClick={() => setCount(count + 1)}>
        点击
      </button>
    </div>
  );
}


与 componentDidMount 或 componentDidUpdate 不同,使用 useEffect 调度的 effect 不会阻塞浏览器更新屏幕,这让你的应用看起来响应更快。大多数情况下,effect 不需要同步地执行。

如果你的 effect 返回一个函数,React 将会在执行清除操作时调用它。

————————————————

版权声明:本文为CSDN博主「前端精髓」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/wu_xianqiang/article/details/100013925