React Hook useEffect缺少依赖项:“列表”

一旦运行以下代码,就会出现以下错误:

React Hook useEffect缺少依赖项:“列表”。包括它或删除依赖项数组react-hooks / exhaustive-deps

我找不到警告的原因。

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;

回答:

在useEffect内部,您正在记录list

console.log(list);

因此,您需要删除上面的行,或者最后添加list到useEffect依赖项。所以改变这条线

}, [term]);

}, [term, list]);

以上是 React Hook useEffect缺少依赖项:“列表” 的全部内容, 来源链接: utcz.com/qa/411362.html

回到顶部