React:api 调用使用状态变量的旧值

时间:2021-04-08 16:26:21

标签: javascript json reactjs ajax react-hooks

我正在尝试在表单提交中使用天气 API 获取数据。对于第一次调用,我没有得到任何结果,然后对于后续调用,我得到前一个表单输入的结果。这可能是什么原因造成的?这是 on submit 处理程序的外观:

const [loc, setLoc] = useState("");
const [weather, setWeather] = useState({});



const handleSubmit = (e) => {
e.preventDefault();
console.log(loc);
const url = `http://api.weatherapi.com/v1/current.json?key=${apikey}&q=${loc}&aqi=no`;
fetch(url)
  .then((res) => {
    return res.json();
  })
  .then((data) => {
    setWeather(data);
    console.log(weather);
  });
  };

这是进行 API 调用时控制台的样子:

enter image description here

1 个答案:

答案 0 :(得分:1)

setWeather 是异步方法,不能在weather 之后立即获取setWeather 的更新值。

    setWeather(data);
    console.log(weather); // This will display old state value of `weather`

您应该使用 useEffect 添加一个 weather 依赖项来检查更新的状态值。

useEffect(() => {
  console.log(weather);
}, [weather]);