小编Ver*_*ird的帖子

什么时候使用useEffect?

我目前正在查看 useEffect 的 react 文档示例

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>
  );
}

Run Code Online (Sandbox Code Playgroud)

我的问题是我们可以轻松地为按钮创建一个 handleClick 函数。我们不必使用 useEffect

const handleButtonClick = () =>{
setCount(count+1)
document.title = `You clicked ${count …
Run Code Online (Sandbox Code Playgroud)

reactjs

26
推荐指数
3
解决办法
9311
查看次数

标签 统计

reactjs ×1