基本反应问题。为什么在 React 文档的这个例子中需要 useEffect?

Basic React question. why is useEffect needed in this example from the React documentation?

react文档中给出了这个例子来说明useEffect的使用

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

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

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

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

不使用 useEffect 就不能重写吗? 为什么首选 useEffect?

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

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

  const handleChange = () => {
      setCount(count + 1);
      document.title = `You clicked ${count} times`;
  }

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

这里有两个问题:

  • 在当前渲染中调用状态 setter 变量 - 您需要等到 下一个 渲染 count待更新,所以

    const handleChange = () => {
        setCount(count + 1);
        document.title = `You clicked ${count} times`;
    }
    

    行不通。您的第二个代码段将在单击后产生 You clicked 0 times

  • 即使这是可能的,当有多个地方可以调用一个状态 setter 时,在每个状态之后放置一些应该发生的事情不是很容易维护 - 它最好能够将该代码放在 运行 之后仅在 一个 位置。