gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:56:05 25 4
gpt4 key购买 nike

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

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

关于reactjs - React Hook useEffect 缺少依赖项 : 'list' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55938884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com