重新调用反应钩子"useEffect"问题



我正在React中进行一个新的小项目,我正在使用React钩子。该应用程序的最终目标是从openweather API获取某个城市的天气数据并将其显示在屏幕上。我创建了一个自定义挂钩来从端点获取数据,并传入了三个参数,如下所示:

export const useHttp = (baseURL, dependancies, isSubmit) => {
// Inizialize isLoading to false 
const [isLoading, setLoading] = useState(false);
// Initialize the fetched data to an empty string
const [fetchedData, setFetchedData] = useState('');
useEffect(() => {
/*Check if isSubmit is true before fetching the corresponding 
data*/
if (isSubmit) {
// set isLoading to true until we get the data
setLoading(true);
// Start fetching the data from the url received
fetch(baseURL)
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch. ');
}
return response.json();
})
// Return the data when fetched successfully
.then(data => {
setLoading(false);
setFetchedData(data);
})
/*Show an alert when fetching encounters an error and stop the 
loader accordingly*/
.catch(err => {
alert("Please insert a valid name")
setLoading(false);
})
}
}, dependancies)
// Returning the data to use them later in displaying the weather
return [isLoading, fetchedData];
};

以下是我的表单组件的工作原理:

// initialized the input to an empty string
const [searchTerm, setSearchTerm] = useState('');
// Initialize the state of submit to false 
const [isSubmit, setIsSubmit] = useState(false);
// Use array destruction to get isLoading and fetchedData from the imported userHttp hook
const [isLoading, fetchedData] = useHttp(`http://api.openweathermap.org/data/2.5/weather?q=${searchTerm}
&APPID=b8c1572d189de60f5480324c6b53d9ab`, [isSubmit], isSubmit);
// Use object destruction to get the desired properties out of the fetched data
const { name, sys, weather, main } = fetchedData ? fetchedData : '';
// Get the user input in the search bar to pass it to submitInput function
const getSearchTerm = (e) => {
setSearchTerm(e.target.value);
}
// Submit the userinput and call the custom hook to fetch the data matched with the input
const submitInput = (event) => {
// Prevent the form from actually submitting
event.preventDefault();
// Change the state of isSubmit so that useEffect can be re-called
setIsSubmit(!isSubmit);
}

正如您所看到的,每当用户提交时,我想更改状态"isSubmit"的值,以便调用useEffect,因为"isSubmite"也作为依赖项传递。此外,我创建了一个条件,以防止useEffect在应用程序渲染时工作,因为我希望它只在用户提交时工作。

问题是,第一次它运行得很好,但当我输入另一个值时,我必须单击两次按钮才能使其运行。我花了一段时间思考这个问题,但最终一无所获。希望有人能帮我。提前谢谢。

这里还有一个指向GitHub上项目代表的链接:https://github.com/Saifsamirk/weatherApp

您的useEffect挂钩仅在isSubmit = true时触发。调用submitInput时,仅将isSubmit的值更改为!isSubmit。它将仅为每秒true。您可能希望在触发事件后将isSubmit状态重置为false。

最新更新