React Hooks 之 useEffect

简介

纯函数

  • 给一个函数同样的参数,那么这个函数永远返回同样的值。

副作用

  • 副作用与纯函数相反,指一个函数处理了与返回值无关的事情。
  • 输入参数一样,而输出结果不确定的情况就是副作用。
  • 纯函数中没有副作用,有副作用的不是纯函数。

React中的副作用有:state状态的改变、生命周期、构建函数…

函数式组件中使用useEffect处理副作用


使用

1. 当第二个参数为一个非空数组时

会在count值发生变化时调用(相当于vue中的watch)

useEffect(() => {
    
    
    document.title = `You clicked ${
      
      count} times`; // 监听count值变化
}, [count])

2. 当第二个参数为一个空数组时

初始化调用一次之后不再执行(相当于componentDidMount)

useEffect(() => {
    
    
    console.log('hello world'); // 仅在初始化时调用一次
}, [])

// 等价于

componentDidMount() {
    
    
    console.log('hello world');
}

3. 当没有第二个参数时

组件的初始化和更新都会执行,(相当于componentDidMount + componentDidUpdate)
容易死循环(夺命连环call)

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

// 等价于

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

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

4. 当返回一个函数时

这个函数会在组件卸载时执行(相当于componentDidMount+componentWillUnmount)

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

// 等价于

componentDidMount() {
    
    
    this.id = setInterval(() => {
    
    
        this.setState({
    
    count: this.state.count + 1})
    }, 1000);
}

componentWillUnmount() {
    
    
    clearInterval(this.id);
}

猜你喜欢

转载自blog.csdn.net/x550392236/article/details/124199443