【问题标题】:Fetch a data from API and map it in table html从 API 获取数据并将其映射到表格 html
【发布时间】:2022-12-07 23:14:30
【问题描述】:

我正在尝试从 api 获取数据并为其构建一个表,但页面中没有任何内容,控制台也没有问题 givit,我的代码是正确的,但有些东西不起作用,返回的数据是一个包含我库存的数组的对象数组信息我需要它进入状态并想要显示它

=>>>app.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>
);

【问题讨论】:

    标签: javascript reactjs api state fetch-api


    【解决方案1】:

    将 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; 
      
    }
    

    【讨论】:

      猜你喜欢
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      • 2020-04-03
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      相关资源
      最近更新 更多