React的SetState没有更新

时间:2020-04-14 03:19:18

标签: reactjs api fetch react-hooks

我正在尝试使用react做一个货币转换器。

我向API发出了请求,我得到了所需的东西。但是当我尝试设置状态时,它给出了未定义的状态。我尝试了其他人的代码,但仍然无法正常工作。

这是代码

import React from 'react';

const API_URL = {MY API URL};

function App() {
  ///////////IMPORTANT////////////
  const [currency, setCurrency] = useState(); 

  //The function to actually make the fetch or request
  function makeApiRequest() {
    fetch(API_URL)
      .then(res => res.json())
      .then(data => {
        setCurrency(data); //Sets currency to data
      });
  }

  //Makes a request to the API
  useEffect(() => {
    makeApiRequest();
    console.log(currency); //Outputs 'undefined'
  }, [])

  ///////////IMPORTANT////////////

  return (
    <h1>Currency Converter</h1>
  );
}

,没有错误,这是数据返回的内容

{rates: {…}, base: "EUR", date: "2020-04-09"}
base: "EUR"
date: "2020-04-09"
rates:
AUD: 1.7444
BGN: 1.9558
BRL: 5.5956
CAD: 1.5265
CHF: 1.0558
CNY: 7.6709
CZK: 26.909
DKK: 7.4657
GBP: 0.87565
HKD: 8.4259
HRK: 7.6175
HUF: 354.76
IDR: 17243.21
ILS: 3.8919
INR: 82.9275
ISK: 155.9
JPY: 118.33
KRW: 1322.49
MXN: 26.0321
MYR: 4.7136
NOK: 11.2143
NZD: 1.8128
PHP: 54.939
PLN: 4.5586
RON: 4.833
RUB: 80.69
SEK: 10.9455
SGD: 1.5479
THB: 35.665
TRY: 7.3233
USD: 1.0867
ZAR: 19.6383

2 个答案:

答案 0 :(得分:0)

由于该函数是异步的,并且useEffect在将初始绘画提交到屏幕之后运行,因此需要花费一些时间,这就是为什么在初始渲染currency上未定义的原因。尝试这种方法。

import React, { useEffect, useState } from "react";

const API_URL = {MY_API_URL};

function App() {
  ///////////IMPORTANT////////////
  const [currency, setCurrency] = useState();

  //The function to actually make the fetch or request
  async function makeApiRequest() {
    const response = await (await fetch(API_URL)).json();
    setCurrency(response);
  }

  //Makes a request to the API
  useEffect(() => {
    makeApiRequest();
  }, []);

   if (currency) {
      console.log(currency);
    }

  return <h1>Currency Converter</h1>;
}

export default App;

答案 1 :(得分:0)

setState异步运行,因此,您要在setState完成设置状态之前注销数据。因此,请尝试以下修改-

import React from 'react';

const API_URL = {MY API URL};

function App() {
 ///////////IMPORTANT////////////
 const [currency, setCurrency] = useState(); 

 //The function to actually make the fetch or request
 function makeApiRequest() {
   fetch(API_URL)
     .then(res => res.json())
     .then(data => {
       setCurrency(data); //Sets currency to data
     });
 }
makeApiRequest();
 //Makes a request to the API
 useEffect(() => {
   console.log(currency); //Outputs 'undefined'
 }, [currency]) //so that this useEffect hooks only runs when the currency changes

 ///////////IMPORTANT////////////

 return (
   <h1>Currency Converter</h1>
 );
}```



You can change back to you're code once you know that setState is working.