首页 > 解决方案 > 无法将用户输入添加到 api

问题描述

这是代码,cosole.log 显示了城市的正确值。城市的值是从另一个 js 文件传递​​的。

import React from 'react';
import  { useState,useEffect } from 'react';
import ReactDOM from 'react-dom';

const Content=(city)=>{

const [cities, setItems] = useState([]);
console.log(city);


useEffect((city) => {
fetch(`http://api.openweathermap.org/data/2.5/forecast?q=${city},LK&mode=json ,appid=5c4420d5c8a61c16e5ee37e4ca265763`)
  .then(res => res.json())
  .then(
    (result) => {
      setItems(cities => cities.concat(result));
    },
  )
  },[]);

  console.log(cities);

 return (
  
  
  <h2>hello</h2>
  );
}


export default Content;

我认为问题出在 ${city} 上,但我尝试了我所知道的一切来解决它。

标签: javascriptreactjsapi

解决方案


我认为问题可能出在 URL 中,其中查询参数有错字(and 之间有一个逗号modeappid它应该是 &)。

它应该是

fetch(`http://api.openweathermap.org/data/2.5/forecast?q=${city},LK&mode=json&appid=5c4420d5c8a61c16e5ee37e4ca265763`)

顺便说一句,mode=json没有必要,因为 JSON 是默认的响应模式。


推荐阅读