Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react useEffect 执行优化 #26

Open
chenhuiYj opened this issue Sep 4, 2020 · 0 comments
Open

react useEffect 执行优化 #26

chenhuiYj opened this issue Sep 4, 2020 · 0 comments

Comments

@chenhuiYj
Copy link
Owner

关于 react useEffect hook 可以看做是 componentDidMount,componentDidUpdate 和 componentWillUnmount 这三个函数的组合。

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

function Example() {
  const [status, setStatus] = useState(false);

  useEffect(() => {
    document.title = `现在状态是:${status?:'开':'关'}`;
  });

  return (
    <div>
      <button onClick={() => useState(!status)}>
        Click me
      </button>
    </div>
  );
}

根据上面的代码,每次点击按钮,都可以改变页面的标题(“开”和“关”的来回切换)

但是问题也出来了,因为 useEffect 在第一次渲染后和每次更新后都会执行。如果页面上有多个 state ,如果只改变了 status ,也会引起整个页面的重新渲染。或者我只想改变 status 的时候,再 useEffect ,其他情况就不执行呢?这个实现不难,只需要加上第二个参数就好

比如想仅当 status 改变再执行,下面的写法就可以实现

useEffect(() => {
    document.title = `现在状态是:${status?:'开':'关'}`;
  },[status]);

比如想 只在第一次渲染后执行一次,下面的的写法就可以实现

useEffect(() => {
    document.title = `现在状态是:${status?:'开':'关'}`;
  },[]);

如此一来,可以避免 useEffect 多次重复的执行,避免一些无用的执行。这样可以实现执行次数上的优化。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant