简体   繁体   English

我正在尝试将 api 中的数据作为我的反应组件中的道具传递,请任何人解释我能做些什么来解决这个问题?

[英]I am trying to pass the data from an api as props in my react components please can anyone explain what i can do to solve the problem?

When the data is fetched from the API it returns an empty object.当从 API 获取数据时,它返回一个空的 object。 Here is the code below.这是下面的代码。 It returns an empty object when I console.log then later brings back the object with data in it.当我使用 console.log 时,它返回一个空的 object,然后稍后带回包含数据的 object。

function App() {

  const [wdata, setWdata] = useState({})

  const API = "62f84860b69bddcd19d34120487d7375"


  useEffect(() => {
    fetch(`https://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=${API}`)
    .then(response => response.json())
    .then(resp => setWdata(resp))
    .catch(error => console.log(error))
  }, [Left])
  console.log(wdata)
 


  return (
    <div className="App">
      <Left className="left" name={wdata.sys.country} temp={wdata.main.temp} description={wdata.weather[0].description} />
      <Right className="right" />
    </div>
  );
}
You can display a loader at the time of fetching data from the Api.
Because data coming from the API needs some time.

Try尝试

function App() {

  const [wdata, setWdata] = useState(null)

  const API = "62f84860b69bddcd19d34120487d7375"

  const fetchData = async() => {
      await fetch(`https://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=${API}`)
.then(response => response.json())
.then(resp => setWdata(resp))
.catch(error => console.log(error))
 }

  useEffect(() => {
    fetchData()
  }, [Left])
  console.log(wdata)
 


  return (
    <div className="App">
{wdata ? <Left className="left" name={wdata.sys.country} temp={wdata.main.temp} description={wdata.weather[0].description} /> : <Left className="left" name={"loading..."} temp={"loading..."} description={"loading..."} /> }
      
      <Right className="right" />
    </div>
  );
}

Apparently using async, await waits for the API to return the response and stores in your state.显然使用异步,await 等待 API 返回响应并存储在您的 state 中。 Before the response is received, your data will be displaying loading...在收到响应之前,您的数据将显示正在加载...

As I said in my comment, the console.log() will always be executed before the .then() calls.正如我在评论中所说, console.log()将始终在.then()调用之前执行。 This is how the JS event loop works.这就是 JS 事件循环的工作方式。 If you want to execute code after setWdata(resp) then simply put that code inside the .then() call.如果你想在setWdata(resp)之后执行代码,那么只需将该代码放在 .then .then()调用中。

useEffect(() => {
  fetch(`https://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=${API}`)
    .then(response => response.json())
    .then(resp => { 
      setWdata(resp);
      doStuffAfter(); // Executes after setWdata
    })
    .catch(error => console.log(error))
}, [Left]);

doStuffBefore(); // Executes before all then() calls

Can you please try this once?你能试试这个吗?

function App() {

  const [wdata, setWdata] = useState({})
  const [isLoading, setIsLoading] = useState(false);

  const API = "62f84860b69bddcd19d34120487d7375"


  useEffect(() => {
    setIsLoading(true);
    fetch(`https://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=${API}`)
    .then(response => response.json())
    .then(resp => setWdata(resp))
    .catch(error => console.log(error))
     setIsLoading(false);
  }, [])
  console.log(wdata)
 
  if(isLoading){
     return <loader/>;
  }

  return (
    <div className="App">
      <Left className="left" name={wdata.sys.country} temp={wdata.main.temp} description={wdata.weather[0].description} />
      <Right className="right" />
    </div>
  );
}

暂无
暂无

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

相关问题 我如何从道具访问我的反应组件中的历史记录? - how can i access the history in my react components from props? 我正在尝试使用 react-redux 存储我的数据,但它没有。 我该如何解决这个问题? - I am trying to store my data using react-redux, but it doesnt. How can I solve this? 没有从 api 获取数据到 web 页面,任何人都可以帮助我解决这个错误,我该怎么做才能获取数据 - Not getting data from api into the web page, can anyone help me through this where I am getting an error and what can i do to get data 请任何人解释 javascript 代码并建议如果一年中的每一天我该怎么做? - Please can anyone explain the javascript code and suggest how can I do if for each day in a year? 如何访问从 API 获取的 object 属性,并将它们传递到我的 React 组件中? - How can i access object properties taken from an API, and pass them into my components in React? 如何将道具传递给来自不同来源的组件? - How can I pass props to components from different sources? 如何通过 props 从 React Router 传递数据? 我做不到 - How to pass Data From React Router through props? I am unable to do it 如何在我的应用程序周围传递道具以反应原生? - How can I pass props around my app in react native? 如何在React中不带道具的情况下将数据传递给组件? - How can I pass data to a component without props in React? 我的渲染有问题,你能给我解释一下吗? - I got a problem with the render, can you explain to me please?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM