简体   繁体   English

useState 没有工作

[英]useState is not woking

can anyone tell me why this country not set in setCountry state via axios.i am fetching data from api via axios.i have below attched my response data from api. can anyone tell me why this country not set in setCountry state via axios.i am fetching data from api via axios.i have below attched my response data from api.

function Country() {
    const [Country, setCountry] = useState([])

    useEffect(()=>{
        //IF [] , runs only once
        const fetchUrl="https://api.first.org/data/v1/countries"
       async function fetchData(){
           
           const request=await axios.get(fetchUrl);
           setCountry(request.data);
           return request;
 
       }
       fetchData();
    
    },[]);

    return (
        <div>
            <button >load country</button>
            <select>
            

            </select>
            
        </div>
    )
}

export default Country

response data from api in console.log console.log 中来自 api 的响应数据

{status: "OK", status-code: 200, version: "1.0", total: 251, limit: 100, …}
access: "public"
data: {DZ: {…}, AO: {…}, BJ: {…}, BW: {…}, BF: {…}, …}
limit: 100
offset: 0
status: "OK"
status-code: 200
total: 251
version: "1.0"

The data you are accessing through API response is an object.您通过 API 响应访问的数据是 object。 Maybe what you can do is something like this -也许你可以做的是这样的 -

setCountry(Object.values(request.data));

The request.data will be an object with below structure - request.data将是具有以下结构的 object -

request.data = {
       "DZ":{"country":"Algeria","region":"Africa"},
       "AO":{"country":"Angola","region":"Africa"},
       "BJ":{country":"Benin","region":"Africa"}
       ....
}

Now passing this into Object.values will return an array which you can directly set into the component state.现在将其传递给Object.values将返回一个数组,您可以将其直接设置到组件 state 中。

Object.values(request.data) = [
   {country: "Algeria", region: "Africa"},
   {country: "Angola", region: "Africa"},
   {country: "Benin", region: "Africa"},
   ....
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM