【问题标题】:How to get object out of React component如何从 React 组件中获取对象
【发布时间】:2022-01-01 22:56:33
【问题描述】:

我正在使用 API 制作天气应用程序,我在函数中使用 API 成功接收数据,但我无法将其从函数中取出

这里是代码

import React, {useState} from 'react'
import {Text, View} from 'react-native'
const axios = require('axios');


let HomeScreen =() => {
  let key = "XXXX"
  axios.get(`https://api.weatherapi.com/v1/current.json?key=${key}&q=London&aqi=no`)
  .then(function (response) {
    // handle success
    console.log(response)
  })
  return(
    <Text>This is {response}</Text>
  )
}

export default HomeScreen

【问题讨论】:

  • 不要将您的个人 API 密钥放入代码示例中!另外,“退出功能”是什么意思?您能否扩展您的示例以显示您想要对响应执行的操作?还是您希望获取的响应位于组件之外?

标签: javascript react-native api axios


【解决方案1】:

如果您想简单地从 API 返回数据,请使用普通的 JS 函数,而不是 React 组件。

function getData() {
  return axios(`https://api.weatherapi.com/v1/current.json?key=${key}&q=London&aqi=no`)
}

它会返回一个你可以在其他地方使用的promise。

async main() {
  const data = await getData();
}

如果您希望您的组件渲染从 API 检索到的数据,您需要采取不同的方式。

在组件安装时使用useEffect 运行一次,并在检索到数据后使用useState 存储数据。然后状态会通知 JSX 如何渲染。

请注意,来自 API 的响应是具有 locationcurrent 属性的对象。你不能仅仅将它添加到 JSX,因为 React 不会接受它。因此,根据您需要从数据中获得什么价值,您需要专门针对它。

这是一个从current 对象的条件对象返回text 值的示例:“天气晴朗”。

const { useEffect, useState } = React;

function Example() {

  // Initialise your state with an empty object
  const [data, setData] = useState({});

  // Call useEffect with an empty dependency array
  // so that only runs once when the component is mounted
  useEffect(() => {

    // Retrieve the data and set the state with it
    async function getData() {
      const key = 'XXX';  
      const data = await axios(`https://api.weatherapi.com/v1/current.json?key=${key}&q=London&aqi=no`)
      setData(data.data);
    }

    getData();

  }, []);

  // If there is no current property provide a message
  if (!data.current) return <div>No data</div>;

  // Otherwise return the current condition text
  return (
    <p>It is {data.current.condition.text}</p>
  );

}

【讨论】:

  • 非常感谢,对我帮助很大!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-17
  • 2019-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-13
相关资源
最近更新 更多