React Hook useEffect缺少一个依赖项:Params



一旦我运行下面的代码,我得到以下错误:

Line 19:5:  React Hook useEffect has missing dependencies: 'departureDate', 'from', and 'to'. Either include them or remove the dependency array  react-hooks/exhaustive-deps

这是我的代码

import axios from 'axios';
import { useEffect, useState } from 'react';
import {Link, useParams} from 'react-router-dom'
function DisplayFlights() {
const {from,to,departureDate} = useParams()
const [flightData,setFlightData] = useState([])
const [isLoading,setLoading]=useState(true)


useEffect(()=>{
axios.get('http://localhost:8081/flightnews/flights?from='+from+'&to='+to
+'&departureDate='+departureDate).then(res=>{
setFlightData(res.data);
setLoading(false);
})
},[])
return (
<div>
<h2>Flights:</h2>
<table>
<thead>
<tr>
<th>Airlines</th>
<th>Departure City</th>
<th>Arrival City</th>
<th>Departure Date and Time</th>
</tr>
</thead>
<tbody>
{!isLoading?flightData.map(flight=><RowCreator item={flight}/>):""}
</tbody>
</table>
</div>
);
}
function RowCreator(props){
var flight = props.item;
return <tr>
<td>{flight.operatingAirlines}</td>
<td>{flight.departureCity}</td>
<td>{flight.arrivalCity}</td>
<td>{flight.estimatedDepartureTime}</td>
<td><Link to={'/passengerDetails/'+flight.id}>Select</Link></td>
</tr>
}
export default DisplayFlights;

我试图在callBack中调用useParams,这样我就可以拥有所有的依赖关系,但我不能这样做,因为它不是一个函数。

谢谢你的帮助

因为你的效果"取决于";对于变量from,todepartureDate,您必须将它们放在依赖数组中:

useEffect(()=>{
// consider adding this so that the UI shows if new data is being fetched.
// setLoading(true);
axios.get('http://localhost:8081/flightnews/flights?from='+from+'&to='+to
+'&departureDate='+departureDate).then(res=>{
setFlightData(res.data);
setLoading(false);
})
},[from, to, departureDate])

现在,你的效果将在这些变量改变时运行,这正是你所需要的。


参见useEffect参考

在这种情况下,我建议您将api调用包装在usecallback钩子中,以避免无限循环。你的代码看起来像这样

const fetchNews=useCallback((from, to, departureDate)=>{
axios.get('http://localhost:8081/flightnews/flights?from='+from+'&to='+to
+'&departureDate='+departureDate).then(res=>{
setFlightData(res.data);
setLoading(false);
})
},[])
useEffect(()=>{
fetchNews(from, to, departureDate)
},[fetchNews,from, to, departureDate])

相关内容

最新更新