簡體   English   中英

React Hook "useForecast" 在 function "getSearch" 中調用,它既不是 React function 組件也不是自定義 React Hook ZC1C425268E68385D1AB5074C17A94F

[英]React Hook "useForecast" is called in function "getSearch" that is neither a React function component nor a custom React Hook function

在這里反應新手!

在我一直從事的 React 天氣儀表板項目中,我一遍又一遍地遇到同樣的問題。 我專注於連接提交函數和我創建的預測 function 以從我正在使用的 OpenWeatherMap API 檢索 json 數據。 在使用我創建的回調 function(從子組件中獲取搜索到的城市值)時,會引發上面列出的錯誤。 由於我沒有打算將回調 function 'getSearch' 用作 function 組件或自定義 React Hook,因此我不知道還有什么可以嘗試修復此錯誤。 下面是我的父組件“overview.js”和子組件“recentSearches.js”的所有代碼:

概述.js

import React, {useState} from 'react';
import './overview.css';
import { RecentSearches } from '../Recent Searches/recentSearches';
import { Hourly } from '../Hourly/hourly';
import { Fiveday } from '../5 Day Forecast/fiveday';

require('dotenv').config(); 

const useForecast = async (city) => {

    // const api_key = process.env.API_KEY;
    const api_key = '2220f5a5d83243938f764759211310';
    var BASE_URL = `http://api.weatherapi.com/v1/forecast.json?key=${api_key}&q=${city}&days=3&aqi=no&alerts=no`;

    const response = await fetch(BASE_URL);
    const data = await response.json();
    console.log(data);
    // collects all of the current weather info for your search
    const currentTempInfo = {
        city: data.location.name, 
        state: data.location.region, 
        epochDate: data.location.localtime_epoch, 
        message: data.current.condition.text, 
        wicon: data.current.condition.icon, 
        currentTemp: data.current.temp_f,
        currentHighTemp: data.forecast.forecastday[0].day.maxtemp_f,
        currentLowTemp: data.forecast.forecastday[0].day.mintemp_f,
        feelsLike: data.current.feelslike_f,
        humidity: data.current.humidity,
        rainLevel: data.current.precip_in,
        // hourlyTemps is an array, starts from midnight(index 0) and goes every hour until 11 pm(index 23)
        hourlyTemps: data.forecast.forecastday[0].hour.map((entry) => {
            let epochTime, temp;
            [epochTime, temp] = [entry.time_epoch, entry.temp_f];
            return [epochTime, temp];
        })
    };
    const daycardInfo = [];

    // this for loop triggers and creates an array with all necessary values for the 
    for (var x in data) {
        const fcDayDates = data.forecast.forecastday[x].date_epoch;
        const dayInfo = data.forecast.forecastday[x].day; 
        const dayValues = {
            dates: fcDayDates, 
            message: dayInfo.condition.text, 
            wicon: dayInfo.condition.icon, 
            maxTemp: dayInfo.maxtemp_f, 
            minTemp: dayInfo.mintemp_f, 
            avgTemp: dayInfo.avgtemp_f
        };
        // pushes dayValues object into daycardInfor array
        daycardInfo.push(dayValues);    
    };

    // this updates the state with the forecast for the city entered
    data = {
        currentTempInfo: currentTempInfo,
        daycardInfo: daycardInfo
    };

    // this spits out the newly created forecast object
    return data;
};

export function Overview() {
    const [search, setSearch] = useState(null);

    // 
    const getSearch = (searchedCity) => {
        setSearch(searchedCity);
        useForecast(search);
    };

    return (
        <div>
            <div class='jumbotron' id='heading-title'>
                <h1>Welcome to <strong>Weathered</strong>!</h1>
                <h3>A Simple Weather Dashboard </h3>
            </div>

            <div class='container-fluid' id='homepage-skeleton'>
                <div class='d-flex' id='center-page'>
                    <RecentSearches callback={callback}/>
        
                    <Hourly />
                </div>
            </div>

            <Fiveday />        
        </div>
    )
};

最近搜索.js

import React, {useState} from 'react';
import './recentSearches.css';

export function RecentSearches({getSearch}) {
    const [city, setCity] = useState('');
    const [recents, setRecents] = useState([]);

    const onSubmit = e => {
        e.preventDefault();
        
        if (!city || city === '') {
            return;
        } else {
            addRecent(city);
            getSearch(city);
        }  
    }
 
    const onChange = (e) => {
        setCity(e.target.value);
    }; 

    // function which takes in searched entry and adds entry to recent searches array
    function addRecent(newSearch) {
        if (recents.includes(newSearch)) {
            return;
        } else {
            setRecents((prev) => [newSearch, ...prev]);
        }
        // clear our search bar entry
        setCity('');
    }; 

    const searchAgain = (e) => {
        const recent = e.target.innerHTML;
        setCity(recent);
    }
    
    return (
        <section id='search-bar-recents'>
            <h3 class='m-3'>Recents </h3>
            <div id='insert-recent-buttons'>{recents.map((entry, index) => <h5 key={index} onClick={searchAgain} value={entry}>{entry}</h5>)}</div>

            <form onSubmit={onSubmit} class="m-3">
                <label className="form-label" for="search-bar">Search A City</label><br/>
                <input className='form-text' id="search-bar" type='text' value={city} placeholder="Las Vegas, etc." onChange={onChange}/>
                <input className='form-button' id='search-button' type='submit' value='Search'/>
            </form>
        </section>
    )
};

任何幫助/提示/注釋表示贊賞! 謝謝!

rules-of-hooks lint 插件使用命名約定來確定哪些函數是自定義鈎子。 由於您的 function 以use開頭,因此 lint 插件假定它是一個鈎子,因此它必須遵循鈎子的規則 但是你的 function 沒有使用任何 react 的內置鈎子,也沒有調用任何自定義鈎子,所以它實際上不需要遵循鈎子的規則。

修復只是重命名 function,所以 lint 插件不認為它是自定義鈎子。 也許fetchForecast

const fetchForecast = async (city) => {
    // const api_key = process.env.API_KEY;
    const api_key = '2220f5a5d83243938f764759211310';
    var BASE_URL = `http://api.weatherapi.com/v1/forecast.json?key=${api_key}&q=${city}&days=3&aqi=no&alerts=no`;
    // ...
}

// Used like:
const getSearch = async (searchedCity) => {
  setSearch(searchedCity);
  const forecast = await fetchForecast(searchedCity);
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

相關問題 React Hook "useRouter" 在 function "article" 中被調用,它既不是 React function 組件也不是自定義 React Hook ZC1C425268E68385D1AB5074C17A94F1 React Hook "useAxios" 在 function "onFinish" 中被調用,它既不是 React function 組件也不是自定義 React Hook ZC1C425268E68385D1AB5074C17ZA4 React Hook "useTranslation" 在 function "getMyMenu" 中被調用,它既不是 React function 組件也不是自定義 React Hook ZC1C425268E68385D1AB5074C17A4 React Hook 在 function 中調用,它既不是 React function 組件,也不是自定義 React Hook function React Hook“useState”在 function“increaseCounter”中被調用,它既不是 React function 組件,也不是自定義 React Hook function 在既不是 React 函數組件也不是自定義 React Hook 函數的函數中調用 React Hook “useAxios” React Hook "useDispatch" 在 function "requestWithAction" 中被調用,它既不是 React function 組件也不是自定義 React Hook ZC1C425268E683854F14ZA7 React Hook "React.useState" 在 function "form" 中調用,它既不是 React function 組件也不是自定義 React Hook ZC1C425268E68385D1AB5074C17A94F React Hook &quot;useContext&quot; 在函數 &quot;age&quot; 中調用,它既不是 React 函數組件,也不是自定義的 React Hook 函數 React Hook &quot;useStyles&quot; 在函數 &quot;appBar&quot; 中調用,它既不是 React 函數組件,也不是自定義 React Hook 函數
 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM