簡體   English   中英

如何在 React.js 中獲取輸入值以獲取 API 數據

[英]How to take an input value to fetch API data in React.js

我想在用戶輸入某種食物(例如意大利面)時進行搜索輸入,然后將輸入插入到指定 ${type} 的 URL 中,以顯示 Spoonacular.com 中的食譜以匹配該用戶輸入和 。

這是我的 Home.js

import React, { useEffect, useState } from "react";
import axios from "axios";
import Recipe from "../components/Recipes";

function Home() {
  const [food, setFood] = useState();
  const [type, setType] = useState();

  const URL = `https://api.spoonacular.com/recipes/complexSearch?apiKey=${APIKey}&query=${type}&number=2`;

  function handleChange(e) {
    setType(e.target.text);
  }

  useEffect(() => {
    axios
      .get(URL)
      .then(function (response) {
        setFood(response.data);
        console.log(URL);
      })
      .catch(function (error) {
        console.warn(error);
      });
  }, []);

  return (
    <main className="App">
      <input
        type="text"
        placeholder="Name of food (e.g. pasta)"
        onChange={handleChange}
      />
      <button onClick={}>Get a Recipe</button>
      <Recipe recipeList={food} />
    </main>
  );
}

export default Home;

這是我的 recipe.js 組件

import React from "react";

function Recipe({ recipeList }) {
  if (!recipeList) return <></>;
  return (
    <div className="recipeCard">
      <h1>{recipeList?.title}</h1>
      <img src={recipeList?.image} alt="Food" />
    </div>
  );
}

export default Recipe;

您需要為 axios 調用指定 GET 查詢參數。 在定義 URL 時,用戶輸入的type尚未定義。

const URL = `https://api.spoonacular.com/recipes/complexSearch`;

const params = {
   apiKey: yourImportedApiKey,
   number: 2,
   query: type
};

// get recipe
const getRecipe = () => {
    axios
      .get(URL, params)
      .then(function (response) {
        setFood(response.data);
        console.log(URL);
      })
      .catch(function (error) {
        console.warn(error);
      });
}

然后將onClick指向您為 axios 調用選擇的提交處理程序名稱。

<button onClick={getRecipe}>Get a Recipe</button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM