简体   繁体   English

从 API 和 map 中获取数据,它在表 html 中

[英]Fetch a data from API and map it in table html

i'm trying to fetch a data from api and build a table for it, but nothing affiched in the page and no probleme givit from console, my code is true but something not work, the data returned is a object contain a arrays i stock the array informations what i need it into state and wante to show it我正在尝试从 api 获取数据并为其构建一个表,但页面中没有任何内容,控制台也没有问题,我的代码是正确的,但有些东西不起作用,返回的数据是一个 object 包含一个 arrays 我库存数组信息我需要它到 state 并想要显示它

=>>>nothing in app.js =>>>app.js 中没有任何内容

index.js索引.js

import { useState }from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';

import reportWebVitals from './reportWebVitals';
import React from 'react';


function Generate(){

  var [items,setItems]=useState([])


  
  var url="https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita";


    fetch(url)
      .then((res) => res.json())
      .then((data) => {
          setItems(data.drinks)

        },
      )
      return items;

  
}

function Work(){
  let data=Generate()

  return(
    <table>
      <tr>
        <th>ID</th>
        <th>LIBELLE</th>
      </tr>
      {
        data.map(elm=>{
          return(
            <tr>
              <td>{elm.idDrink}</td>
              <td>{elm.strDrink}</td>
            </tr>
          )
        })
      }




    </table>



  )




}
export default function App() {

  <Work />
 
 
 }

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

Move the api call inside the useEffect将 api 调用移到 useEffect 中

function Generate(){

  const [items,setItems]=useState([]) 
  
  const url="https://www.thecocktaildb.com/api/json/v1/1/search.php?s=margarita";

  useEffect(() => {

    fetch(url)
      .then((res) => res.json())
      .then((data) => {
          setItems(data.drinks)

        },
      )
   }, [])
   
  return items; 
  
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM