无法为每个返回的元素创建一个 UUID?
Can't Create A UUID For Every Element Returned?
我正在创建一个使用 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:
在我的 Recipe 组件中,创建一个名为 id 的变量并将其设置为 UUID()。接下来,将此变量作为 props 传递到我的 map 函数中。此解决方案的问题在于它创建了一个对所有食谱都相同的 UUID。
解决方案尝试 2
在我的 Recipe 组件和我的 map 函数中,创建一个名为 Id 的道具并将其传递给它:i.uuid()。但是,我收到未处理的拒绝 (TypeError): i.uuid is not a function error。
这是从 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
},
如有任何建议或反馈,我们将不胜感激!
使用 map() 将 hits 数组更新为 return 一个以 uniqueId 作为附加键的新数组。这可以使用 ES6 传播语法
来实现
const updatedHits = response.hits.map((recipe) => {
uniqueId: uuid(),
...recipe
});
setRecipe(updatedHits);
我也遇到了如何获取recipe ID的问题。最后,我找到了一个解决方案,也许这会对你有所帮助。
首先,每个食谱都有来自 Edamam API 的独特 'uri'。在 uri 中,您将能够找到食谱 ID(在“#recipe_”之后)。
因此,您可以尝试使用像这样的小函数从 uri 字符串中提取 ID:
extractIdFromUri(uri) {
return uri.split('#recipe_').pop()
}
对我有用。
我正在创建一个使用 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:
在我的 Recipe 组件中,创建一个名为 id 的变量并将其设置为 UUID()。接下来,将此变量作为 props 传递到我的 map 函数中。此解决方案的问题在于它创建了一个对所有食谱都相同的 UUID。
解决方案尝试 2
在我的 Recipe 组件和我的 map 函数中,创建一个名为 Id 的道具并将其传递给它:i.uuid()。但是,我收到未处理的拒绝 (TypeError): i.uuid is not a function error。
这是从 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
},
如有任何建议或反馈,我们将不胜感激!
使用 map() 将 hits 数组更新为 return 一个以 uniqueId 作为附加键的新数组。这可以使用 ES6 传播语法
来实现const updatedHits = response.hits.map((recipe) => {
uniqueId: uuid(),
...recipe
});
setRecipe(updatedHits);
我也遇到了如何获取recipe ID的问题。最后,我找到了一个解决方案,也许这会对你有所帮助。
首先,每个食谱都有来自 Edamam API 的独特 'uri'。在 uri 中,您将能够找到食谱 ID(在“#recipe_”之后)。
因此,您可以尝试使用像这样的小函数从 uri 字符串中提取 ID:
extractIdFromUri(uri) {
return uri.split('#recipe_').pop()
}
对我有用。