修复 useEffect React Hook 中缺少对象时缺少依赖项警告?

时间:2021-06-10 19:23:52

标签: reactjs date react-hooks

所以我得到了一个包含一系列基于以下值的开关的页面:

const [values, setValues] = useState({
    asthma: "off",
    infectiousDisease: "off",
    bleedingDisorder: "off",
    cancer: "off",
    diabetes: "off",
    epilepsy: "off",
    hivAids: "off",
    stroke: "off",
    heartDisease: "off",
    hbp: "off",
    immuneDisorders: "off",
    lungDisease: "off",
    mentalDisorder: "off",
    rheumaticDisease: "off",
    smokeTobaccoProducts: "off",
    radiationTherapy: "off",
    eatingDisorders: "off",
    entDisorders: "off",

    latex: "off",
    localAnasthetics: "off",
    metals: "off",
    penicillin: "off",
    pollen: "off",
    foods: "off",

    bleedingGums: "off",
    bruxism: "off",
    halitosis: "off",
    ulcer: "off",
    dryMouth: "off",
    soreJawM: "off",
  });

现在,当用户访问此页面时,我希望根据后端保存的内容设置值。后端返回一个包含值的数组,我在 useEffect() 中设置它们。但是我只希望这发生一次。这是从 spring 后端设置值的代码。

useEffect(() => {
    getDoH().then(
      (response) => {
        let newValues = values;
        let valueArray = Object.entries(newValues).map((v, index) => {
          v[1] = response.data.switchValues[index]
          return v
      });
      newValues = Object.fromEntries(valueArray);
      setValues({...newValues});
      },
      (error) => {
        console.log(error);
      }
    );
  },[]);

getDoH 函数只是一个 axios.get 请求。该函数工作正常,但我在终端中收到此警告:“第 142:5 行:React Hook useEffect 缺少依赖项:'values'。要么包含它,要么删除依赖项数组 react-hooks/exhaustive-deps”

现在我知道我可以禁用它,但无论如何只能修复它吗?将值添加到 },[]);不是一个选项,因为我不希望每次更改开关时它都运行,因为这基本上会使开关不起作用。

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

您可以传递 setValues() 一个函数,该函数根据之前的状态更新状态。该函数采用先前的状态并返回新状态。这样,您就不必引用在 values 钩子之外定义的 useEffect()

例如

useEffect(() => {
  setValues((state) => generateNewStateFromPrev(state));
}, []);

这是 documentation on this

答案 1 :(得分:1)

您可以将对象存储为常量而不是状态,这也会使您的代码更清晰。 react-hooks/exhaustive-deps 是正确的,从代码的含义来看,您希望运行一个依赖于该 values 状态的函数。因此,在一般情况下,如果 values 发生变化并且效果取决于它,您最终会处于不一致的状态。

但您的意图是代码不依赖于状态,而是依赖于它的初始值。你可以做这样的事情。

const defaultIllnesses = {asthma: "off",  infectiousDisease: "off",...};

function myComp () {
  const [values, setValues] = useState(defaultIllnesses);

  useEffect(() => {
    getDoH().then(
      (response) => {
        const valueArray = Object.entries(defaultIllnesses)
   ...
  }, [defaultIllnesses]); // this const is still a dependency, but it won't change 
  

有一些变体,例如将疾病作为数组 ['asthma', 'infectiousDisease', ...] 但这只是语法糖。您还可以查看 Array.reduce 来遍历数组并从中创建一个对象。