【问题标题】:How to render API response into a tabular form in react js如何在 React js 中将 API 响应呈现为表格形式
【发布时间】:2020-11-08 23:20:36
【问题描述】:

我正在尝试创建一个反应应用程序,在该应用程序中,它基于表单输入调用 API 并以 json 格式提供响应,我希望此 json 以表格格式呈现。但是表格不应该在初始页面加载期间显示,它应该只在 API 获取之后显示。请提出任何通过 react js 实现此目的的方法。

下面是我的代码:

APP.js:

import React, { useState } from "react";
import "./App.css";
import Axios from "axios";import { v4 as uuidv4 } from "uuid";
import Recipe from "./components/Recipe";
import Alert from "./components/Alert";

function App() {
  const [query, setQuery] = useState("");
  const [recipes, setRecipes] = useState([]);
  const [alert, setAlert] = useState("");

  const url = `https://api.edamam.com/search?q=${query}&app_id=${APP_ID}&app_key=${APP_KEY}`;

  const getData = async () => {
    if (query !== "") {
      const result = await Axios.get(url);
      if (!result.data.more) {
        return setAlert("No food with such name");
      }
      console.log(result);
      setRecipes(result.data.hits);
      setQuery("");
      setAlert("");
    } else {
      setAlert("Please fill the form");
    }
  };

  const onChange = e => setQuery(e.target.value);

  const onSubmit = e => {
    e.preventDefault();
    getData();
  };

  return (
    <div className="App">
      <h1>Food Searching App</h1>
      <form onSubmit={onSubmit} className="search-form">
        {alert !== "" && <Alert alert={alert} />}
        <input
          type="text"
          name="query"
          onChange={onChange}
          value={query}
          autoComplete="off"
          placeholder="Search Food"
        />
        <input type="submit" value="Search" />
      </form>
      <div className="recipes">
        {recipes !== [] &&
          recipes.map(recipe => <Recipe key={uuidv4()} recipe={recipe} />)}
      </div>
    </div>
  );
}

export default App;

在上面的return()中定义表格也显示了带有表格的表格。(只有在API调用成功后才能显示表格并且应该包含API数据)欢迎任何建议或任何资源材料参考。

【问题讨论】:

    标签: reactjs forms axios


    【解决方案1】:

    你能把这部分转换成下面的部分吗

      <div className="recipes">
        {
          recipes.length > 0 
          ? <table>
              <tr>
                {
                  recipes.map(recipe => <Recipe key={uuidv4()} recipe={recipe} />)
                }
              </tr>
            </table>
           : null
        }
      </div>
    

    只有在收到响应时才会呈现表格。

    【讨论】:

    • 谢谢 Sridhar 的建议,显然它抛出了新的 err0r 作为“错误:元素类型无效:需要一个字符串(对于内置组件)或一个类/函数(对于复合组件)但是得到:未定义。您可能忘记从定义组件的文件中导出组件,或者您可能混淆了默认导入和命名导入。请检查 App 的渲染方法。"​​
    • 我应该使用 而不是
      。你现在可以试试吗? (我已经编辑了我的更改)
    猜你喜欢
    • 1970-01-01
    • 2020-07-30
    • 2018-08-08
    • 2021-09-23
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-19
    相关资源
    最近更新 更多