使用 useEffect,如何跳过在初始渲染时应用效果? [英] With useEffect, how can I skip applying an effect upon the initial render?

查看:14
本文介绍了使用 useEffect,如何跳过在初始渲染时应用效果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 React 的新效果挂钩,如果某些值在重新渲染之间没有更改,我可以告诉 React 跳过应用效果 - React 文档中的示例:

With React's new Effect Hooks, I can tell React to skip applying an effect if certain values haven't changed between re-renders - Example from React's docs:

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes

但上面的示例将效果应用于初始渲染,以及 count 已更改的后续重新渲染.如何告诉 React 跳过初始渲染的效果?

But the example above applies the effect upon initial render, and upon subsequent re-renders where count has changed. How can I tell React to skip the effect on the initial render?

推荐答案

如指南所述,

Effect Hook,useEffect,增加了从函数组件执行副作用的能力.它的用途与 React 类中的 componentDidMount、componentDidUpdate 和 componentWillUnmount 相同,但统一到一个 API 中.

The Effect Hook, useEffect, adds the ability to perform side effects from a function component. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API.

在本指南的示例中,预计 count 仅在初始渲染时为 0:

In this example from the guide it's expected that count is 0 only on initial render:

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

所以它将作为 componentDidUpdate 使用额外的检查:

So it will work as componentDidUpdate with additional check:

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

这基本上是可以用来代替 useEffect 的自定义钩子的工作方式:

This is basically how custom hook that can be used instead of useEffect may work:

function useDidUpdateEffect(fn, inputs) {
  const didMountRef = useRef(false);

  useEffect(() => {
    if (didMountRef.current) { 
      return fn();
    }
    didMountRef.current = true;
  }, inputs);
}

感谢 @Tholle 建议 useRef 而不是 setState.

Credits go to @Tholle for suggesting useRef instead of setState.

这篇关于使用 useEffect,如何跳过在初始渲染时应用效果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆