React Hook useEffect 缺少依赖项:'list' [英] React Hook useEffect has a missing dependency: 'list'

查看:63
本文介绍了React Hook useEffect 缺少依赖项:'list'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行以下代码后,出现以下错误:

<块引用>

React Hook useEffect 缺少依赖项:'list'.要么包括它要么删除依赖数组 react-hooks/exhaustive-deps

我找不到警告的原因.

import React, { useState, useEffect } from 'react';从 'axios' 导入 axios;从'./Form'导入表单;const App = () =>{const [term, setTerm] = useState('pizza');const [list, setList] = useState([]);const submitSearch = e =>{e.preventDefault();setTerm(e.target.elements.receiptName.value);};useEffect(() => {(异步术语 => {const api_url = 'https://www.food2fork.com/api';const api_key = '<我的 API 密钥>';const 响应 = 等待 axios.get(`${api_url}/search?key=${api_key}&q=${term}&count=5`);setList(response.data.recipes);控制台日志(列表);})(学期);}, [学期]);返回 (<div className="应用程序"><header className="App-header"><h1 className="App-title">食谱搜索</h1></标题><Form submitSearch={submitSearch}/>{学期}

);};导出默认应用程序;

解决方案

Inside your useEffect you are logging list:

console.log(list);

因此您要么需要删除上面的行,要么将 list 添加到最后的 useEffect 依赖项中.所以改变这一行

}, [term]);

}, [term, list]);

Once I run the below code, I get the following error:

React Hook useEffect has a missing dependency: 'list'. Either include it or remove the dependency array 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:

console.log(list);

So you either need to remove the above line, or add list to the useEffect dependencies at the end. so change this line

}, [term]);

to

}, [term, list]);

这篇关于React Hook useEffect 缺少依赖项:'list'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆