218

根据文档:

componentDidUpdate()在更新发生后立即调用。初始渲染不调用此方法。

我们可以使用新的useEffect()钩子来模拟componentDidUpdate(),但它似乎useEffect()在每次渲染后都运行,即使是第一次。如何让它不在初始渲染时运行?

正如您在下面的示例中所见,componentDidUpdateFunction在初始渲染期间打印,但在初始渲染componentDidUpdateClass期间未打印。

function ComponentDidUpdateFunction() {
  const [count, setCount] = React.useState(0);
  React.useEffect(() => {
    console.log("componentDidUpdateFunction");
  });

  return (
    <div>
      <p>componentDidUpdateFunction: {count} times</p>
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        Click Me
      </button>
    </div>
  );
}

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

  componentDidUpdate() {
    console.log("componentDidUpdateClass");
  }

  render() {
    return (
      <div>
        <p>componentDidUpdateClass: {this.state.count} times</p>
        <button
          onClick={() => {
            this.setState({ count: this.state.count + 1 });
          }}
        >
          Click Me
        </button>
      </div>
    );
  }
}

ReactDOM.render(
  <div>
    <ComponentDidUpdateFunction />
    <ComponentDidUpdateClass />
  </div>,
  document.querySelector("#app")
);
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="app"></div>

4

11 回答 11

211

我们可以使用useRef钩子来存储我们喜欢的任何可变值,因此我们可以使用它来跟踪useEffect函数是否是第一次运行。

如果我们希望效果在相同的阶段运行componentDidUpdate,我们可以使用useLayoutEffect

例子

const { useState, useRef, useLayoutEffect } = React;

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

  const firstUpdate = useRef(true);
  useLayoutEffect(() => {
    if (firstUpdate.current) {
      firstUpdate.current = false;
      return;
    }

    console.log("componentDidUpdateFunction");
  });

  return (
    <div>
      <p>componentDidUpdateFunction: {count} times</p>
      <button
        onClick={() => {
          setCount(count + 1);
        }}
      >
        Click Me
      </button>
    </div>
  );
}

ReactDOM.render(
  <ComponentDidUpdateFunction />,
  document.getElementById("app")
);
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="app"></div>

于 2018-11-11T22:50:34.660 回答
122

您可以将其转换为自定义 hooks,如下所示:

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

const useDidMountEffect = (func, deps) => {
    const didMount = useRef(false);

    useEffect(() => {
        if (didMount.current) func();
        else didMount.current = true;
    }, deps);
}

export default useDidMountEffect;

使用示例:

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

import useDidMountEffect from '../path/to/useDidMountEffect';

const MyComponent = (props) => {    
    const [state, setState] = useState({
        key: false
    });    

    useEffect(() => {
        // you know what is this, don't you?
    }, []);

    useDidMountEffect(() => {
        // react please run me if 'key' changes, but not on initial render
    }, [state.key]);    

    return (
        <div>
             ...
        </div>
    );
}
// ...
于 2019-09-15T05:32:31.397 回答
53

我做了一个简单的useFirstRender钩子来处理像关注表单输入这样的情况:

import { useRef, useEffect } from 'react';

export function useFirstRender() {
  const firstRender = useRef(true);

  useEffect(() => {
    firstRender.current = false;
  }, []);

  return firstRender.current;
}

它从 开始true,然后切换到falseuseEffect它只运行一次,再也不会运行。

在您的组件中,使用它:

const firstRender = useFirstRender();
const phoneNumberRef = useRef(null);

useEffect(() => {
  if (firstRender || errors.phoneNumber) {
    phoneNumberRef.current.focus();
  }
}, [firstRender, errors.phoneNumber]);

对于您的情况,您只需使用if (!firstRender) { ....

于 2020-09-07T10:59:01.773 回答
8

@ravi,你的不调用传入的卸载函数。这是一个更完整的版本:

/**
 * Identical to React.useEffect, except that it never runs on mount. This is
 * the equivalent of the componentDidUpdate lifecycle function.
 *
 * @param {function:function} effect - A useEffect effect.
 * @param {array} [dependencies] - useEffect dependency list.
 */
export const useEffectExceptOnMount = (effect, dependencies) => {
  const mounted = React.useRef(false);
  React.useEffect(() => {
    if (mounted.current) {
      const unmount = effect();
      return () => unmount && unmount();
    } else {
      mounted.current = true;
    }
  }, dependencies);

  // Reset on unmount for the next mount.
  React.useEffect(() => {
    return () => mounted.current = false;
  }, []);
};

于 2020-04-02T20:46:56.160 回答
8

与Tholle 的答案相同的方法,但使用useState而不是useRef.

const [skipCount, setSkipCount] = useState(true);

...

useEffect(() => {
    if (skipCount) setSkipCount(false);
    if (!skipCount) runYourFunction();
}, [dependencies])

编辑

虽然这也有效,但它涉及更新状态,这将导致您的组件重新渲染。如果您的所有组件useEffect调用(以及所有子组件的调用)都有一个依赖数组,这无关紧要。但请记住,任何useEffect没有依赖数组 (useEffect(() => {...})将再次运行。

使用和更新useRef不会导致任何重新渲染。

于 2021-08-08T17:52:10.657 回答
2

@MehdiDehghani,您的解决方案工作得非常好,您必须做的一个补充是卸载,将didMount.current值重置为false. 何时尝试在其他地方使用此自定义挂钩,您不会获得缓存值。

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

const useDidMountEffect = (func, deps) => {
    const didMount = useRef(false);

    useEffect(() => {
        let unmount;
        if (didMount.current) unmount = func();
        else didMount.current = true;

        return () => {
            didMount.current = false;
            unmount && unmount();
        }
    }, deps);
}

export default useDidMountEffect;
于 2020-02-19T18:01:47.130 回答
2

这是迄今为止我使用typescript. 基本上,这个想法是一样的,Ref但我也在考虑返回的回调useEffect来对组件卸载执行清理。

import {
  useRef,
  EffectCallback,
  DependencyList,
  useEffect
} from 'react';

/**
 * @param effect 
 * @param dependencies
 *  
 */
export default function useNoInitialEffect(
  effect: EffectCallback,
  dependencies?: DependencyList
) {
  //Preserving the true by default as initial render cycle
  const initialRender = useRef(true);

  useEffect(() => {
    let effectReturns: void | (() => void) = () => {};

    // Updating the ref to false on the first render, causing
    // subsequent render to execute the effect
    if (initialRender.current) {
      initialRender.current = false;
    } else {
      effectReturns = effect();
    }

    // Preserving and allowing the Destructor returned by the effect
    // to execute on component unmount and perform cleanup if
    // required.
    if (effectReturns && typeof effectReturns === 'function') {
      return effectReturns;
    } 
    return undefined;
  }, dependencies);
}

你可以像往常一样简单地使用它,useEffect但是这一次,它不会在初始渲染上运行。以下是如何使用这个钩子。

useuseNoInitialEffect(() => {
  // perform something, returning callback is supported
}, [a, b]);
于 2021-08-04T18:41:29.193 回答
0

一种简单的方法是let从您的组件中创建一个 , 并将其设置为 true。

然后说如果它的真设置为假然后返回(停止)useEffect函数

像那样:


    import { useEffect} from 'react';
    //your let must be out of component to avoid re-evaluation 
    
    let isFirst = true
    
    function App() {
      useEffect(() => {
          if(isFirst){
            isFirst = false
            return
          }
    
        //your code that don't want to execute at first time
      },[])
      return (
        <div>
            <p>its simple huh...</p>
        </div>
      );
    }

它类似于@Carmine Tambasciabs 解决方案,但不使用状态:) ‍‍‍‍‍‍ ‍‍‍‍‍‍‍‍‍‍‍‍‍‍</p>

于 2022-02-16T22:39:37.353 回答
0

简化实施

import { useRef, useEffect } from 'react';

function MyComp(props) {

  const firstRender = useRef(true);

  useEffect(() => {
    if (firstRender.current) {
      firstRender.current = false;
    } else {
      myProp = 'some val';
    };

  }, [props.myProp])


  return (
    <div>
      ...
    </div>
  )

}
于 2022-03-03T19:18:07.807 回答
-1

之前的一切都很好,但是考虑到 useEffect 中的操作可以“跳过”放置一个基本上不是第一次运行并且仍然具有依赖关系的 if 条件(或任何其他),这可以通过更简单的方式实现。

例如,我有以下情况:

  1. 从 API 加载数据,但我的标题必须是“正在加载”,直到日期不存在,所以我有一个数组,游览开始时为空并显示文本“正在显示”
  2. 使用与这些 API 不同的信息呈现组件。
  3. 用户可以将这些信息一个一个地删除,甚至一开始都让tour数组为空,但这一次API获取已经完成
  4. 一旦通过删除旅行列表为空,然后显示另一个标题。

所以我的“解决方案”是创建另一个 useState 来创建一个布尔值,该值仅在数据获取后才更改,使 useEffect 中的另一个条件为 true,以便运行另一个也取决于游览长度的函数。

useEffect(() => {
  if (isTitle) {
    changeTitle(newTitle)
  }else{
    isSetTitle(true)
  }
}, [tours])

这里是我的 App.js

import React, { useState, useEffect } from 'react'
import Loading from './Loading'
import Tours from './Tours'

const url = 'API url'

let newTours

function App() {
  const [loading, setLoading ] = useState(true)
  const [tours, setTours] = useState([])
  const [isTitle, isSetTitle] = useState(false)
  const [title, setTitle] = useState("Our Tours")

  const newTitle = "Tours are empty"

  const removeTours = (id) => {
    newTours = tours.filter(tour => ( tour.id !== id))

    return setTours(newTours)
  }

  const changeTitle = (title) =>{
    if(tours.length === 0 && loading === false){
      setTitle(title)
    }
  }

const fetchTours = async () => {
  setLoading(true)

  try {
    const response = await fetch(url)
    const tours = await response.json()
    setLoading(false)
    setTours(tours)
  }catch(error) {
    setLoading(false)
    console.log(error)
  }  
}


useEffect(()=>{
  fetchTours()
},[])

useEffect(() => {
  if (isTitle) {
    changeTitle(newTitle)
  }else{
    isSetTitle(true)
  }
}, [tours])


if(loading){
  return (
    <main>
      <Loading />
    </main>
  )  
}else{
  return ( 

    <main>
      <Tours tours={tours} title={title} changeTitle={changeTitle}           
removeTours={removeTours} />
    </main>
  )  
 }
}



export default App
于 2021-11-05T15:16:43.123 回答
-2

如果你想跳过第一次渲染,你可以创建一个状态“firstRenderDone”,并在 useEffect 中将其设置为 true,并且依赖列表为空(类似于 didMount)。然后,在你的另一个 useEffect 中,你可以在做某事之前检查第一次渲染是否已经完成。

const [firstRenderDone, setFirstRenderDone] = useState(false);

//useEffect with empty dependecy list (that works like a componentDidMount)
useEffect(() => {
  setFirstRenderDone(true);
}, []);

// your other useEffect (that works as componetDidUpdate)
useEffect(() => {
  if(firstRenderDone){
    console.log("componentDidUpdateFunction");
  }
}, [firstRenderDone]);
于 2021-09-23T19:42:00.880 回答