【问题标题】:How should I use a variable of a function as a prop in React JS我应该如何在 React JS 中使用函数的变量作为道具
【发布时间】:2021-07-18 09:28:10
【问题描述】:
import React, { useState } from 'react'
import Display from './components/Display';
const App = () => {
    const [input,setInput] = useState("");
    
    const getData = async () => {
    const myAPI = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${input}&units=metric&appid=60dfee3eb8199cac3e55af5339fd0761`);
    const response = await myAPI.json();
    console.log(response);                  //want to use response as a prop in Display component
   }

   return(
    <div className="container">
        <h1>Weather Report</h1>
        <Display title={"City Name :"} />         //here
        <Display title={"Temperature :"} />       //here
        <Display title={"Description :"} />       //here
        <input type={input} onChange={e => setInput(e.target.value)} className="input"/>
        <button className="btn-style" onClick={getData}>Fetch</button>
    </div>
   );
}

export default App;

【问题讨论】:

  • 您可以在 API 响应中使用另一个 useState。像const [response, setResponse] = useState({}),然后在getData中调用setResponse(response),并将响应传递给Display组件
  • 请解释一下您要实现的目标,以及您指的是哪个功能?
  • @GouthamJ.M 我只想将响应(对象)传递到 组件中,例如

标签: reactjs async-await fetch-api react-props


【解决方案1】:

我不知道我是否理解正确,但如果我是对的,您想访问从 API 获取的函数返回的数据,如果是这样,您可以尝试这种方式

import React, { useState, useEffect } from 'react' 
import Display from './components/Display';
import axios from 'axios';

const App = () => {
const [input,setInput] = useState(""); 

const [state, setState] = useState({loading: true, fetchedData: null});

useEffect(() => {
        getData();
}, [setState]);

async function getData() {
    setState({ loading: true });
    const apiUrl = 'http://api.openweathermap.org/data/2.5/weather?q=${input}&units=metric&appid=60dfee3eb8199cac3e55af5339fd0761';
    await axios.get(apiUrl).then((repos) => {
        const rData = repos.data;
        setState({ loading: false, fetchedData: rData });
    });
}

return(
    state.loading ? <CircularProgress /> : ( 
        <List className={classes.root}>
        { state.fetchedData.map((row) => ( 
            <div className="container">
                <h1>Weather Report</h1>
                <Display title={"City Name :" + row.cityName } />         //here
                <Display title={"Temperature :" + row.temperature} />       //here
                <Display title={"Description :" + row.description} />       //here
                 
            </div>
        )) }
        </List>
    )
);

}

【讨论】:

  • 你导入的那个axios是什么?
  • 这只是一个包,可以很容易地向 REST 端点发送异步 HTTP 请求并执行 CRUD 操作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
  • 2021-04-05
  • 2020-05-15
  • 2019-01-10
  • 2020-10-24
  • 1970-01-01
相关资源
最近更新 更多