首页 > 解决方案 > 不能为返回的每个元素创建一个 UUID?

问题描述

我正在创建一个使用 edamam API 的简单食谱应用程序。从 edamam 返回的数据没有每个配方元素的唯一 ID。因此,我尝试使用 UUID 为所有返回的食谱创建唯一的 Id。但是,我应用的解决方案都没有创建唯一的 id。

我的食谱组件

import React, {useState, useEffect} from 'react';
import Recipe_Tiles from './Recipe_Tiles'
import { API_ID, API_KEY} from '../../Config'
import uuid from 'uuid/v4'



import '../../App.css'


function Recipe() {

  //Initialized states
  const [Search, setSearch] = useState("");
  const [Term, setTerm] = useState();
  const [Recipe, setRecipe] = useState([]);

  let id = uuid();



//useEffect will run again if the Term state is updated
  useEffect(() => {
      getAPI();
  }, [Term]);

//method to retrieve recipes
  const getAPI = () => {
    fetch(`https://api.edamam.com/search?q=${Term}&app_id=${API_ID}&app_key=${API_KEY}`)
    .then(response => response.json())
    .then(response => {
      console.log(response)
      setRecipe(response.hits)
    })
  }

  const handleChange = (e) => {
    setSearch(e.target.value);
  }

 const handleSubmit = (e) => {
   e.preventDefault();
   setTerm(Search);
   setSearch("");
 }

  return (
    <div 
    className="App"
    style = {{marginLeft: "15px"}}
    >

        <h1 style = {{textAlign: 'center'}}>The Recipe App</h1>

      <form  onSubmit = {handleSubmit}>
      <div className="row inputs">
        <div className="input-field col s6">
        <label htmlFor="first_name"> Search for Recipes</label>
          <input 
          className = "recipe-input"
          type = "text"
          value = {Search}
          onChange = {handleChange}
          />
        </div>
        <button 
            className="btn waves-effect waves-light button-input" 
            type="submit"
            onSubmit = {handleSubmit} 
            name="action">Search
              <i className="material-icons right">local_dining</i>
          </button>
    </div>
    </form>

   {/* 
   The recipe tiles component is used to create the recipe cards.
   Once data is retrieved from the API, it'll be passed as props to the component. 
   */}
    {Recipe.map(i => (
      <Recipe_Tiles 
      title = {i.recipe.label} 
      calories = {i.recipe.calories}
      image = {i.recipe.image}
      URL = {i.recipe.url}
      ingredients = {i.recipe.ingredients}
      id = {id}
       />
    ))}

    </div>
  );
}

export default Recipe;

我的 Recipe_Tiles 组件:

import React from 'react'

export default function Recipe_Tiles ({title, calories, image, URL,ingredients, id}) {

    return(
        <div class="card">

        <div class="card-image waves-effect waves-block waves-light">
          <img class="activator" src={image} alt = "this is a recipe"/>
        </div>
        <div class="card-content">

          <span class="card-title activator grey-text text-darken-4" 
          style = {{fontSize: '15px',lineHeight:'20px', fontWeight: '700'}}>{title}
                <i class="material-icons right">more_vert</i>
          </span>
          <br />
          <hr style = {{width: '40%', marginLeft: '90px', marginBottom: '10px'}}/>
            <p> Calories: {Math.floor(calories)} | Ingredients: {ingredients.length}</p>
          <br />
          <p><a href={URL}>View The Complete Recipe Here</a></p>
        </div>

        <div class="card-reveal">
          <span 
          class="card-title grey-text text-darken-4"
          style = {{fontSize: '15px', lineHeight:'20px', fontWeight: '700', marginRight: '20px',marginTop: '50px'}}>
              Ingredients List:<i class="material-icons right">close</i></span>
              <ol>
                  {ingredients.map(i => (
                      <li style = {{marginLeft: '-40px'}}>{i.text}</li>
                  ))}
              </ol>
           <p>My id is {id}</p>
        </div>
      </div>

    )
}

解决方案尝试1:

在我的食谱组件中,创建一个名为 id 的变量并将其设置为 UUID()。接下来,将此变量作为道具传递给我的地图函数。这个解决方案的问题是它创建了一个对所有配方都相同的 UUID。

解决方案尝试 2

在我的 Recipe 组件和 map 函数中,创建一个名为 Id 的道具并将其传递给它:i.uuid()。但是,我收到 Unhandled Rejection (TypeError): i.uuid is not a function 错误。

以下是 Edamam 的 API 返回的数据:

q: "chicken",
from: 0,
to: 10,
more: true,
count: 168106,
hits: [
{
recipe: {
uri: "http://www.edamam.com/ontologies/edamam.owl#recipe_b79327d05b8e5b838ad6cfd9576b30b6",
label: "Chicken Vesuvio",
image: "https://www.edamam.com/web-img/e42/e42f9119813e890af34c259785ae1cfb.jpg",
source: "Serious Eats",
url: "http://www.seriouseats.com/recipes/2011/12/chicken-vesuvio-recipe.html",
shareAs: "http://www.edamam.com/recipe/chicken-vesuvio-b79327d05b8e5b838ad6cfd9576b30b6/chicken",
yield: 4,
dietLabels: [],
healthLabels: [],
cautions: [],
ingredientLines: [],
ingredients: [],
calories: 4055.7632762010808,
totalWeight: 2765.5901364771207,
totalTime: 60,
totalNutrients: {},
totalDaily: {},
digest: []
},
bookmarked: false,
bought: false
},
{
recipe: {
uri: "http://www.edamam.com/ontologies/edamam.owl#recipe_8275bb28647abcedef0baaf2dcf34f8b",
label: "Chicken Paprikash",
image: "https://www.edamam.com/web-img/e12/e12b8c5581226d7639168f41d126f2ff.jpg",
source: "No Recipes",
url: "http://norecipes.com/recipe/chicken-paprikash/",
shareAs: "http://www.edamam.com/recipe/chicken-paprikash-8275bb28647abcedef0baaf2dcf34f8b/chicken",
yield: 4,
dietLabels: [],
healthLabels: [],
cautions: [],
ingredientLines: [],
ingredients: [],
calories: 3033.2012500008163,
totalWeight: 1824.6125000003276,
totalTime: 0,
totalNutrients: {},
totalDaily: {},
digest: []
},
bookmarked: false,
bought: false
},

任何建议或反馈将不胜感激!

标签: javascriptreactjsuuidedamam-api

解决方案


我也遇到了关于如何获取配方 ID 的问题。最后,我找到了一个解决方案,也许这会对你有所帮助。

首先,每个配方都有一个来自 Edamam API 的独特“uri”。在 uri 中,您将能够找到配方 ID(在 '#recipe_ 之后)。

因此,您可以尝试使用这样的小函数从 uri 字符串中提取 ID:

extractIdFromUri(uri) {
    return uri.split('#recipe_').pop()
}

它对我有用。


推荐阅读