ReactJS 应用程序:我需要单击一个按钮两次才能检索 API 调用?

ReactJS app: I need to click a button twice to retrieve API call?

大家好,我在 React 中构建了一个天气应用程序,我想将状态变量“city”设置为输入值,以便我可以将其重新插入 API URL 但我必须单击两次才能使 API 正确显示。第一次点击返回“错误:请求失败,状态代码为 400”。

这是我从以下位置获得 API 的地方:

const URL = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${APIKey}`;

这是我的 API 电话:

  const getCity = () => {
    axios
      .get(URL)
      .then(function (response) {
        setWeatherData(response.data);
      })
      .catch(function (err) {
        console.warn(err);
      });
  };

这是我遇到问题的函数...

  function handleChange() {
    const bar = document.getElementById("input-field").value;
    if (bar.indexOf(" ") > -1) {
      setCity(bar.split(" ").join("+"));
    } else {
      setCity(bar);
    }
  }

这是 JSX:

 <input
   id="input-field"
   className="searchbar"
   type="text"
   placeholder="Name of city (e.g. Austin"
  />
  <button
    className="searchbtn"
    onClick={() => {
      handleChange();
      getCity();
    }}
  >
    search
  </button>

问题是 cityURL 仅在下一次渲染时计算,而不是立即计算。

从您的 onClick 处理程序中删除 getCity() 并将其添加到依赖于 city

useEffect()
useEffect(() => {
  axios.get("https://api.openweathermap.org/data/2.5/weather", {
    params: {
      q: city,
      appid: APIKey
    }
  })
  .then(({ data }) => setWeatherData(data))
  .catch(console.warn)
}, [ city ])