1

在我见过的大多数反应示例中,人们似乎避免将代码直接放入功能组件的主体中,而是将其包装到useEffect(() => {...}). 例如在官方文档中

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

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

为什么这比简单地写更好:

function Example() {
  const [count, setCount] = useState(0);
  document.title = `You clicked ${count} times`;

  return (...);
}

在这两种情况下,文档标题都将在每个渲染上设置。(我相信useEffect()代码是渲染之后执行的,但这在这个例子中似乎不相关,对吧)

我理解useEffect()if 的价值:

  • 状态作为第二个参数传递,因此代码不会在每次渲染时执行,而是针对指定的状态更改执行。
  • 我们利用了清理机制。

But without that? Is there still a reason to wrap your code into useEffect()?

4

3 回答 3

0

Answering my own question. As far as I can tell now, there is no reason or justification to have a useEffect() without the second parameter in your code.

The reason why tutorials like the one on reactjs.org use it that way seems to be for educational reasons only: They probably want you to focus on something else and not confuse you with that second parameter. However this can lead to the (false) impression that the second parameter is not always necessary.

Once again, this was a lesson for me that tutorial code is not always ready to be used in real projects. Also in a real project, lint rules like react-hooks/exhaustive-deps (by default included in create-react-app) would immediately tell you that useEffect() without a second parameter is not ok.

于 2020-03-25T10:54:14.453 回答
-3
useEffect(() => {
    document.title = `You clicked ${count} times`;
  },[count]);

The code should be like that because now useEffect will only call when count state will change

于 2020-01-29T10:05:51.613 回答
-4

See the official doc here about useEffect hook. The useEffect is similar to componentDidMount, componentDidUpdate, and componentWillUnmount combined. Does it give you any hint?

于 2020-01-29T10:30:26.733 回答