如果我在React的useEffect第二个参数中添加多个依赖项怎么办?

时间:2019-03-08 16:27:01

标签: reactjs react-hooks

例如,如果我将一个useEffect挂钩为useEffect(() => {...},[a,b])。如果[a,b]之一更改或两个[a,b]都更改,useEffect会被解雇吗?

1 个答案:

答案 0 :(得分:7)

任何一个更改时都会触发。想到它的方法是,您正在告诉React:

  

ab是我在此效果中使用的东西,因此,如果其中任何一个   更改后,我的效果将需要清理旧版本并使用更新后的值重新执行。

这是一个简单的示例,可让您查看行为:

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

function App() {
  const [dependency1, setDependency1] = useState(1);
  const [dependency2, setDependency2] = useState(1);
  useEffect(
    () => {
      console.log("only dependency1", dependency1, dependency2);
    },
    [dependency1]
  );
  useEffect(
    () => {
      console.log("dependency1 and dependency2", dependency1, dependency2);
    },
    [dependency1, dependency2]
  );
  return (
    <div className="App">
      <button
        onClick={() => {
          setDependency1(prev => prev + 1);
        }}
      >
        Change dependency1
      </button>
      <button
        onClick={() => {
          setDependency2(prev => prev + 1);
        }}
      >
        Change dependency2
      </button>
      <button
        onClick={() => {
          setDependency1(prev => prev + 1);
          setDependency2(prev => prev + 1);
        }}
      >
        Change both
      </button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Edit useEffect dependencies