如何解决API搜索将信息保存在不同的位置 React.js
我正在尝试寻找一种食物,并使用USDA的api显示食物中的蛋白质含量。当我搜索“ apple”并登录console.log时,得到以下结果:
因此,要获取蛋白质,我只需要以下代码:
const protein = res['data']['foods']['0']['foodNutrients']['8']['value'];
this.setState({ protein })
我遇到的问题是当我搜索“橙色”时:
蛋白质与我输入的代码位于不同的区域,并且出现以下错误:
Unhandled Rejection (TypeError): res.data.foods[0].foodNutrients[8] is undefined
我了解为什么会收到错误,但我不知道如何设置功能或组件来解决此问题。如果结果根据搜索而出现在稍微不同的位置上,那么如何针对不同的食物搜索获得相同的属性(蛋白质)?
这是到目前为止的完整代码:
import React from 'react';
import './App.css';
import axios from 'axios'
export default class App extends React.Component {
state = {
protein: "",calories: "",caloriesName: "",}
clickHandler = (event) => {
if (event.keyCode === 13) {
const query = event.target.value;
const API_KEY = '*********'
axios.get(`https://api.nal.usda.gov/fdc/v1/foods/search?api_key=${API_KEY}&query=${query}`)
.then(res => {
//find protein
const target = 'nutrientName'
function filter(data,target){
return data.filter(item => item[target])
}
var x = res['data']['foods']['0']['foodNutrients']
const c = filter(x,target)
console.log(c)
console.log(res)
const protein = res['data']['foods']['0']['foodNutrients']['8']['value'];
this.setState({ protein })
const calories = res['data']['foods']['0']['foodNutrients']['10']['value'];
this.setState({ calories })
})
}
}
render() {
return (
<div>
<h1>{this.state.protein} </h1>
<h1>{this.state.calories} </h1>
<input onKeyDown={event => this.clickHandler(event)} />
</div>
)
}
}
解决方法
您可以设置一个对json对象中的键进行迭代的函数。
看看 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
它可以给你一个主意。
,编写一个方法,该方法将遍历对象数组并根据提供的数据过滤项目。这里我们需要检查关键的“营养”等于“蛋白质”
document.getElementById("changeSubContent").innerHTML = "Your Text";
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。