一旦运行以下代码,我就会收到以下错误:
React Hook useEffect 缺少依赖项:“list”。请添加它或删除依赖项数组 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:
list
console.log(list);
因此,您要么需要删除上面的行,要么list在末尾添加到 useEffect 依赖项。因此,将此行更改为
}, [term]);
到
}, [term, list]);