React JS -值未从App.js传递到元素

dba5bblo  于 2023-04-07  发布在  React
关注(0)|答案(2)|浏览(121)

我开始学习React JS,所以我m trying to build an app that makes cotation and I m试图将cotation值作为prop传递。
但是它不起作用,请帮帮忙!
谢谢!

import './App.css';
import RealDolar from './components/real_dolar.js';

function App() {
  let realDolar = 0;
  let url = 'https://api.freecurrencyapi.com/v1/latest?base_currency=USD&currencies=BRL&apikey=xyz';
  fetch(url).then(res=>{
    return res.json()
  }).then(json=>{
    realDolar = json['data']['BRL'];
  })
  return (
    <div className="Real_Rapido">
      <RealDolar cotacao={realDolar} />
    </div>
  );
}
export default App;
rsl1atfo

rsl1atfo1#

您好!您需要使用useStateuseEffect钩子。
了解更多关于hooks的信息:https://react.dev/reference/react/useStatehttps://react.dev/reference/react/useEffect

import './App.css';
import RealDolar from './components/real_dolar.js';
    
function App() {
  const [realDolar, setRealDolar] = useState(0);
  const url = 'https://api.freecurrencyapi.com/v1/latest? 
  base_currency=USD&currencies=BRL&apikey=xyz';

  useEffect(() => {
    fetch(url).then(res=>{
      return res.json()
    }).then(json=>{
      setRealDolar(json['data']['BRL']);
    })
  }, [])
     
  return (
    <div className="Real_Rapido">
      <RealDolar cotacao={realDolar} />
      </div>
  );
}

export default App;
wvyml7n5

wvyml7n52#

传递的prop应该是一个state:

function App() {
  const [realDolar, setRealDolar] = useState(0);
  useEffect(() => {
    let url = 'https://api.freecurrencyapi.com/v1/latest?base_currency=USD&currencies=BRL&apikey=xyz';
    fetch(url).then(res=>{
      return res.json()
    }).then(json=>{
      setRealDolar(json['data']['BRL'])
    })
  }, [])
  return (
    <div className="Real_Rapido">
      <RealDolar cotacao={realDolar} />
    </div>
  );
}

相关问题