您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使用useEffect,如何跳过对初始渲染的效果?

使用useEffect,如何跳过对初始渲染的效果?

如指南所述,

效果挂钩(useEffect)增加了从功能组件执行副作用的功能。它的作用与React类中的componentDidMount,componentDidUpdate和componentWillUnmount相同,但统一为一个API。

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

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

因此,它将componentDidUpdate与其他检查一起使用:

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

基本上,这是可以使用而不是可以使用的自定义挂钩的useEffect工作方式:

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

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

致谢@Tholle useRef而不是进行建议setState

其他 2022/1/1 18:20:30 有395人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶