简体   繁体   English

React Hook useEffect 缺少依赖项:'list'

[英]React Hook useEffect has a missing dependency: 'list'

Once I run the below code, I get the following error:运行以下代码后,出现以下错误:

React Hook useEffect has a missing dependency: 'list'. React Hook useEffect 缺少依赖项:'list'。 Either include it or remove the dependency array react-hooks/exhaustive-deps包括它或删除依赖数组 react-hooks/exhaustive-deps

I cannot find the reason for the warning.我找不到警告的原因。

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Form from './Form';

const App = () => {
  const [term, setTerm] = useState('pizza');
  const [list, setList] = useState([]);

  const submitSearch = e => {
    e.preventDefault();
    setTerm(e.target.elements.receiptName.value);
  };

  useEffect(() => {
    (async term => {
      const api_url = 'https://www.food2fork.com/api';
      const api_key = '<MY API KEY>';

      const response = await axios.get(
        `${api_url}/search?key=${api_key}&q=${term}&count=5`
      );

      setList(response.data.recipes);
      console.log(list);
    })(term);
  }, [term]);

  return (
    <div className="App">
      <header className="App-header">
        <h1 className="App-title">Recipe Search</h1>
      </header>
      <Form submitSearch={submitSearch} />
      {term}
    </div>
  );
};

export default App;

Inside your useEffect you are logging list :在您的 useEffect 中,您正在记录list

console.log(list);

So you either need to remove the above line, or add list to the useEffect dependencies at the end.所以你要么需要删除上面的行,要么在最后添加list到 useEffect 依赖项。 so change this line所以改变这一行

}, [term]);

to

}, [term, list]);

You can disable the lint warning by writing:您可以通过以下方式禁用 lint 警告:

// eslint-disable-next-line react-hooks/exhaustive-deps
}, [term]);

You can disable this by inserting a comment您可以通过插入评论来禁用此功能

// eslint-disable-next-line // eslint-disable-next-line

The dependency array - it's the second optional parameter in the useEffect function. dependency array ——它是useEffect函数中的第二个可选参数。 React will recall function defined in the first parameter of useEffect function if parameters inside dependency array will changed from the previous render.如果dependency array中的参数与之前的渲染不同,React 将调用useEffect函数的第一个参数中定义的函数。

Then you doesn't need to place list variable inside dependency array .然后你不需要将list变量放在dependency array中。

  useEffect(() => {
    // do some

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [term]);

This warning comes beacuse you have a state 'list' being used inside useEffect.出现此警告是因为您在 useEffect 中使用了状态“列表”。 So react warns you that 'list' is not added to dependency so any changes to 'list' state won't trigger this effect to run again.因此 React 会警告您“列表”未添加到依赖项,因此对“列表”状态的任何更改都不会触发此效果再次运行。
You can find more help here您可以在此处找到更多帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM