返回

useEffect 第二个参数是怎么处理的

前端

useEffect 第二个参数的作用

useEffect 第二个参数是依赖项数组,它是一个数组,其中包含了回调函数所依赖的变量或状态。当依赖项数组中的任何一个值发生变化时,回调函数就会被再次调用。

例如,以下代码中的回调函数依赖于组件的 state 变量 count

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

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

  useEffect(() => {
    console.log(`The count is now ${count}`);
  }, [count]);

  return (
    <div>
      <p>The count is {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment count</button>
    </div>
  );
};

export default MyComponent;

当组件第一次渲染时,回调函数会被调用,并输出 "The count is now 0"。当用户点击按钮,调用 setCount 方法将 count 的值增加 1 时,回调函数也会再次被调用,并输出 "The count is now 1"

第二个参数为空数组时的处理

如果 useEffect 的第二个参数是一个空数组,则回调函数只会在组件第一次渲染时执行。这对于那些不需要在组件每次渲染时都执行的副作用操作非常有用。

例如,以下代码中的回调函数只会在组件第一次渲染时执行一次,它会获取一个随机数并将其存储在组件的 state 变量 randomNumber 中:

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

const MyComponent = () => {
  const [randomNumber, setRandomNumber] = useState(0);

  useEffect(() => {
    const randomNumber = Math.random();
    setRandomNumber(randomNumber);
  }, []);

  return (
    <div>
      <p>The random number is {randomNumber}</p>
    </div>
  );
};

export default MyComponent;

如何优化性能

useEffect 的第二个参数对于优化 React 项目的性能非常重要。通过仔细选择依赖项数组,我们可以减少回调函数的调用次数,从而提高组件的性能。

例如,以下代码中的回调函数依赖于组件的 state 变量 countname

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

const MyComponent = () => {
  const [count, setCount] = useState(0);
  const [name, setName] = useState('');

  useEffect(() => {
    console.log(`The count is now ${count} and the name is ${name}`);
  }, [count, name]);

  return (
    <div>
      <p>The count is {count}</p>
      <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
      <button onClick={() => setCount(count + 1)}>Increment count</button>
    </div>
  );
};

export default MyComponent;

当用户在输入框中输入文字时,组件的 state 变量 name 会发生变化,导致回调函数再次被调用。然而,count 的值并没有发生变化,因此回调函数的调用是多余的。

我们可以通过修改依赖项数组来优化这个组件。我们可以将 name 从依赖项数组中移除,这样回调函数就不会在 name 发生变化时被调用了:

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

const MyComponent = () => {
  const [count, setCount] = useState(0);
  const [name, setName] = useState('');

  useEffect(() => {
    console.log(`The count is now ${count}`);
  }, [count]);

  return (
    <div>
      <p>The count is {count}</p>
      <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
      <button onClick={() => setCount(count + 1)}>Increment count</button>
    </div>
  );
};

export default MyComponent;

现在,当用户在输入框中输入文字时,回调函数不会再被调用了,从而提高了组件的性能。

总结

useEffect 的第二个参数是依赖项数组,它对于优化 React 项目的性能非常重要。通过仔细选择依赖项数组,我们可以减少回调函数的调用次数,从而提高组件的性能。