【问题标题】:ReactJS Hooks. TypeError: Object(...) is not a function [closed]ReactJS 钩子。 TypeError:Object(...)不是函数[关闭]
【发布时间】:2020-11-06 06:38:14
【问题描述】:

我是 reactJS 的新手,我正在尝试使用 React Hooks 开发一个天气应用程序。 useEffect 钩子无限运行,甚至依赖和以前一样。所以我决定使用 useCallBack 钩子,但是它显示了一个错误。

代码如下:

import React,{useState,useEffect,useCallBack} from 'react';
import axios from 'axios';

const WeatherApp = () =>{
  const [weatherData,setWeatherData] = useState({
    latitude:1,
    longitude:0,
    city:'',
    country:'',
    description:'',
    temperature:'',
    apiKey:"96f70a610a2b066259b75fc8d23eab98",
    icon:''
  });

  const getWeatherByCoords = useCallBack(()=>{
    let api=`http://api.openweathermap.org/data/2.5/weather?lat=${weatherData.latitude}&lon=${weatherData.longitude}&appid=${weatherData.apiKey}`;

    axios.get(api)
      .then(res=>{
        const data = res.data;
        setWeatherData(pre=>({...pre,
          country:data.sys.country,
          city:data.name,
          temperature:data.main.temp,
          description:data.weather[0].description
        }));
        console.log(weatherData);

      })
      .catch(error=>errorHandler(error));
  },[weatherData]);


  const errorHandler = error=>{
    console.log(error);
  }
 useEffect(()=>{
   // const interval = setInterval(()=>{
     if(navigator.geolocation){
     navigator.geolocation.getCurrentPosition(position=>{
       setWeatherData({...weatherData,
         latitude:position.coords.latitude,
         longitude:position.coords.longitude});
       getWeatherByCoords();
     },error=>errorHandler(error),{timeout:10000});
   }
 // },1000);
   // return(()=> clearInterval(interval));
},[getWeatherByCoords]);

  // fetch(`api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${key}`)

  return(
    <div>
      <div>
        <h1>City</h1>
        <h2>Date</h2>
        <h3>Description</h3>
      </div>
      <div>
        <img alt='This is an img'></img>
        <h2>Temperature</h2>
        <p> <span>°C</span>|<span>°F</span></p>
      </div>
    </div>
  )
};

export default WeatherApp;

错误:

如果我使用useMemo,错误会变成:getWeatherByCoords is not a function。我很迷茫。我花了一整天的时间在这上面。如果有人能提供帮助,非常感谢。

【问题讨论】:

  • 错字:useCallBack -> useCallback
  • 非常感谢。这是一个愚蠢的错误。现在可以了。 useEffect 挂钩仍然一直在运行。你知道出了什么问题吗?
  • 我认为你应该删除useEffect中的依赖getWeatherByCoords,只留下一个空数组:[]

标签: reactjs react-hooks usecallback


【解决方案1】:

useEffectuseCallback 将在依赖项更改时运行。

因此,如果您的依赖项是要在钩子内更改的依赖项,它将触发一个循环。

你不需要useCallback

只需在useEffect内部触发axios API方法,然后设置weatherData的状态不带任何依赖即可。

【讨论】:

  • 谢谢,但是,如果我删除依赖项,weatherDate 将永远不会更新。一直是初始状态。
  • 没有依赖数组怎么样。比如 useEffect(() => { ...在这里调用你的 api });不要'console.log(weatherData);因为 react 会提示你添加 weatherData 作为依赖。如果你想看看它是否有效,只需 { JSON.stringify(weatherData) } 在 JSX 中。如果它正在工作,请删除测试的字符串。
猜你喜欢
  • 2020-04-15
  • 2020-06-04
  • 1970-01-01
  • 2018-04-22
  • 1970-01-01
  • 1970-01-01
  • 2020-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多