首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >反应- .map返回的不是一个函数?

反应- .map返回的不是一个函数?
EN

Stack Overflow用户
提问于 2022-05-06 21:45:27
回答 2查看 48关注 0票数 0

我遵循这个例子:https://reactjs.org/docs/faq-ajax.html

但是我的代码是返回的,weather.map不是函数吗?

代码语言:javascript
运行
复制
function App(props) {

  const [weather, setWeather] = useState([]);

  useEffect(() => {
    fetch("https://api.openweathermap.org/data/2.5/weather?q=kalamazoo&appid=XXXXXXXXXXXX")
    .then(res => res.json())
    .then(
      (result) => {
      setWeather(result)
      console.log(result)
      }
    )
  },[])

  return (
    <div className="App">
      {weather.map(item => (
        <li key={item.id}>{item.main}</li>
      ))}
      
    </div>
  );
}

export default App;

我知道它需要一个数组,但是即使API没有返回,我仍然会得到错误。

EN

回答 2

Stack Overflow用户

发布于 2022-05-06 21:53:35

openweathermap /weather API返回一个对象。您可以查看他们的昂首阔步,了解APIs的详细信息及其确切的响应格式。

要访问天气信息,您需要执行以下操作:

代码语言:javascript
运行
复制
useEffect(() => {
    fetch(
        'https://api.openweathermap.org/data/2.5/weather?q=kalamazoo&appid=XXXXXXXXXXXX'
    )
        .then((res) => res.json())
        .then((result) => {
            setWeather(result.weather); // this is where weather data array is present
            console.log(result);
        });
}, []);
票数 2
EN

Stack Overflow用户

发布于 2022-05-06 22:05:36

映射不是函数错误意味着weather数据类型不是数组,因此它没有映射函数,API返回对象,所以可以使用直接映射代替

代码语言:javascript
运行
复制
Object.values(weather || {}).map((item)=>{
  return(
   <li key={item.id}>{item.main}</li>
 )
})
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72147663

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档