React在使用Hooks获取API数据时没有更新状态。

huangapple go评论80阅读模式
英文:

React not updating state on fetching API data by hooks

问题

I am trying to implement api calls via hooks, but I don't know why the state is not updating . Could someone look at this and tell me the reason:

import React, { useState } from 'react';

function Weather() {
    var [weat, setWeat] = useState({ city: '', report: [] })
    var UpdateCity = event => {
        setWeat({ ...weat, city: event.target.value });
    }
    var UpdateReport = event => {
        var addr = "http://api.openweathermap.org/data/2.5/weather?q=" + weat.city + "&appid=04e"
        console.log(addr);
        fetch(addr)
            .then(res => res.json())
            .then(res => {
                setWeat({ ...weat, report: res });
            });

    }
    return (
        <>
            <h1>Welcome to my weather App</h1>
            <h3>Please enter your city</h3>
            <input type='text' onChange={UpdateCity} placeholder='Enter your City'></input>
            <input type='submit' onClick={UpdateReport}></input>
        </>
    )
}

export default Weather;
英文:

I am trying to implement api calls via hooks, but I don't know why the state is not updating . Could someone look at this and tell me the reason:

import React,{useState} from &#39;react&#39;;

function Weather(){
    var [weat,setWeat]=useState({city:&#39;&#39;,report:[]})
    var UpdateCity = event =&gt;{
        setWeat({...weat,city:event.target.value});
    }
    var UpdateReport = event =&gt;{
        var addr=&quot;http://api.openweathermap.org/data/2.5/weather?q=&quot;+weat.city+&quot;&amp;appid=04e&quot;
        console.log(addr);
        fetch(addr)
        .then(res=&gt;res.json())
        .then(res=&gt;{
            setWeat({...weat,report:res});
        });
        
    }
    return(
        &lt;&gt;
            &lt;h1&gt;Welcome to my weather App&lt;/h1&gt;
            &lt;h3&gt;Please enter your city&lt;/h3&gt;
            &lt;input type=&#39;text&#39; onChange={UpdateCity} placeholder=&#39;Enter your City&#39;&gt;&lt;/input&gt;
            &lt;input type=&#39;submit&#39; onClick={UpdateReport}&gt;&lt;/input&gt;
        &lt;/&gt;
    )
}

export default Weather;

答案1

得分: 1

你没有传递认证密钥,所以基本上会出现错误,因为你没有处理错误情况,这就是为什么你没有看到错误。

所以,你需要按照以下方式更新代码,并在 URL 中传递密钥以获取数据。

除此之外,代码看起来没问题

var UpdateReport = event => {
    var addr = "http://api.openweathermap.org/data/2.5/weather?q=" + weat.city + "&appid=04e"
    console.log(addr);
    fetch(addr)
    .then(res => res.json())
    .then(res => {
        setWeat({...weat, report: res});
    })
    .catch(error => {
        console.log(error)
    })
}

更新

所以问题不是更新状态,而是出现了跨域问题。查看具有示例 API 的工作代码沙箱此处

英文:

You are not passing a key for authentication, so its basically going to error, since you doesn't handle error cases thats why you are not seeing it

So you need to update as follows and pass the key on the url to get the data.

Apart from that code looks fine

var UpdateReport = event =&gt;{
        var addr=&quot;http://api.openweathermap.org/data/2.5/weather?q=&quot;+weat.city+&quot;&amp;appid=04e&quot;
        console.log(addr);
        fetch(addr)
        .then(res=&gt;res.json())
        .then(res=&gt;{
            setWeat({...weat,report:res});
        })
        .catch(error =&gt; {
          console.log(error)
        })

    }

Update

So the problem was not updating the state, there was a cors issue. See the working codesandbox with a sample api here,

答案2

得分: 0

你的 API URL 中只是缺少了 s。我相信调用只能通过 HTTPS 进行。

https://api.openweathermap.org/.....

此外,正如 @DILEEP THOMAS 提到的,最好添加一个 catch 块,这将帮助你了解为什么 fetch 不正常工作。

.catch(err => console.log(err.message))
英文:

You are just missing the s in your API URL. I believe calls only work through HTTPS

https://api.openweathermap.org/.....

Also, as @DILEEP THOMAS mention, its better to add catch block that will help you know why fetch is not working properly.

.catch(err =&gt; console.log(err.message))

答案3

得分: 0

I just copied your code in local and added my own API Key and works out of the box. When testing the app have the chrome console openned and check for the error fetching the data, to see if you have an error on the request.

Also your query might be working and you don't see your component re-render as you are not using weat object inside the return, please add some log before the return just with this:

console.log("weat.city: ", weat.city, " weat.report: ", weat.report)

So now you will see if the state changes or not.

英文:

I just copied your code in local and added my own API Key and works out of the box. When testing the app have the chrome console openned and check for the error fetching the data, to see if you have an error on the request.

Also your query might be working and you don't see your component re-render as you are not using weat object inside the return, please add some log before the return just with this:

   console.log(&quot;weat.city: &quot;, weat.city, &quot; weat.report: &quot;, weat.report)
   return (
      . . . 
   )

So now you will see if the state changes or not.

huangapple
  • 本文由 发表于 2020年1月6日 17:33:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/59609653.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定