从异步函数中访问数据 – React JS

huangapple go评论74阅读模式
英文:

Accessing data from async function - React JS

问题

export const service_query = async function(url){
  const resp = await fetch(url);
  const result = await resp.json();
  const features = result.features;
  const features_list = []
  for (let i = 0; i < features.length; i++){
    features_list.push(features[0].attributes)
  }
  return features_list;
}
import './App.css';
import { service_query } from './Utils';
import Table from './Table'';

function App() {
  const url = "
"
;
const headers = []; const content = []; useEffect(() => { const fetchData = async () => { const data_values = await service_query(url); headers = Object.keys(data_values[0]); content = Object.values(data_values); }; fetchData(); }, [url]); return ( <div className="App"> <header className="App-header"> <h1>Test</h1> <div className="container"> <Table theadData={headers} tbodyData={content}/> </div> </header> </div> ); } export default App;

In the updated code, I've used the useEffect hook to make the asynchronous data fetch and populate the headers and content variables when the component mounts. This way, you can access the data and use it to render the table. Please make sure to import useEffect from React at the beginning of your component file.

英文:

I'm trying to query a data service and use the json response to create a table with React. I have the following async function that creates a list of the json response (this part works as intended):

export const service_query = async function(url){
  const resp = await fetch(url);
	const result = await resp.json();
  const features = result.features;
  const features_list = []
  for (let i = 0; i < features.length; i++){
    features_list.push(features[0].attributes)
  }
  return features_list;
}

I'm not too familiar with async functions and am having trouble accessing the data. I've checked similar questions on here and haven't gotten a clear answer. My research shows that I need to need to call the async function with an await but that can only be done inside another async function, which once again returns a promise when called without await. I'm stuck in this loop...

import './App.css';
import { service_query } from './Utils';
import Table from './Table';

function App() {
  const url = "
"; const data_values = service_query(url) const headers = Object.keys(data_values[0]) const content = Object.values(data_values) return ( <div className="App"> <header className="App-header"> <h1>Test</h1> <div className="container"> <Table theadData={headers} tbodyData={content}/> </div> </header> </div> ); } export default App;

I've tried the following but this once again means I can't access the data and get the promise:

 const getData = async() => {
    const data_values = await service_query(url)
    return data_values
  }; 

I also tried the following, but can't access data_values outside the function and assigning the entire thing to a variable returns a promise again:

  service_query(url).then((data) => {
    const data_values = data
  });

答案1

得分: 2

你可以在useEffect中进行异步调用,并使用useState更新响应。类似于以下内容:

const url = '一些URL'
function App() {
  const [headers, setHeaders] = useState(null);
  const [content, setContent] = useState(null);

  useEffect(() => {
    service_query(url).then(response => {
       setHeaders(response[0]);
       setContent(response);
    })
  }, [])

  return (
    <div className="App">
      <header className="App-header">
        <h1>测试</h1>  
        <div className="container">
          {!!headers && !!content && (
            <Table theadData={headers} tbodyData={content}/>
          )}
        </div>
      </header>
    </div> 
  );
}
英文:

You can make async calls within useEffect, and update the response with useState. Something like this:

const url = &#39;some url&#39;
function App() {
  const [headers, setHeaders] = useState(null);
  const [content, setContent] = useState(null);

  useEffect(() =&gt; {
    service_query(url).then(response =&gt; {
       setHeaders(response[0]);
       setContent(response);
    })
  }, [])

  return (
    &lt;div className=&quot;App&quot;&gt;
      &lt;header className=&quot;App-header&quot;&gt;
        &lt;h1&gt;Test&lt;/h1&gt;  
        &lt;div className=&quot;container&quot;&gt;
          {!!headers &amp;&amp; !!content &amp;&amp; (
            &lt;Table theadData={headers} tbodyData={content}/&gt;
          )}
        &lt;/div&gt;
      &lt;/header&gt;
    &lt;/div&gt; 
  );
}

huangapple
  • 本文由 发表于 2023年3月4日 00:02:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75629338.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定