我正在制作食谱应用。我正在使用Yummly API我得到了一个响应但是我很困惑如何渲染我从API返回的数据,因为响应是一个带有一个配方数组的Object。当我尝试渲染数组时,我收到此错误:
未捕获(承诺)错误:对象无效作为React子对象(找到:具有键{objectUrlsBySize,sourceDisplayName,ingredients,id,smallImageUrls,recipeName,totalTimeInSeconds,attributes,flavors,rating}的对象)。如果您要渲染子集合,请使用数组。
链接到API响应的图像:
Object from API “匹配”是我想要在我的组件中呈现的部分
Action.js
import Axios from 'axios';
import {LOOK_UP_RECIPE`enter code here`} from './types';
const API_ID = '########';
const API_KEY = '######';
const ROOT_LOOK_UP_URL = `http://api.yummly.com/v1/api/recipes?
_app_id=${API_ID}&_app_key=${API_KEY}`
export function lookuprecipesYummly(ingredients) {
const yummlyurl =`${ROOT_LOOK_UP_URL}&q=${ingredients}`;
const request = Axios.get(yummlyurl);
return {
type: LOOK_UP_RECIPE,
payload: request
};
}
Reducer.js
import { LOOK_UP_RECIPE } from '../actions/types'
export default function(state = [], action) {
console.log(action)
switch (action.type){
case LOOK_UP_RECIPE:
return [ action.payload.data, ...state ];
default:
return state;
}
}
组件:
import _ from "lodash";
import React, {Component} from 'react';
import { connect } from 'react-redux';
class RecipeList extends Component {
renderRecipe(recipeData) {
return (
<tr key={0}>
<td key={1}>{recipeData.matches}</td>
</tr>
)
}
render() {
return(
<table>
<thead>
<tr key={1}>
<th>Recipe</th>
</tr>
</thead>
<tbody>
{this.props.recipes.map(this.renderRecipe)}
</tbody>
</table>
)
}
}
function mapStateToProps({recipes}) {
return {
recipes
}
};
export default connect(mapStateToProps)(RecipeList);
答案 0 :(得分:0)
您需要在某些JSX内使用每个食谱的数据。以下是如何填充表格行的示例:
import _ from "lodash";
import React, {Component} from 'react';
import { connect } from 'react-redux';
class RecipeList extends Component {
renderRecipe(recipe) {
return (
<tr key={recipe.id}>
<td>{recipe.recipeName}</td>
<td>{recipe.rating}</td>
<td>{recipe.attributes.course[0]}</td>
<td>{recipe.ingredients.join(', ')}</td>
</tr>
)
}
render() {
return(
<table>
<thead>
<tr>
<th>Recipe</th>
<th>Rating</th>
<th>Course</th>
<th>Ingredients</th>
</tr>
</thead>
<tbody>
{this.props.recipes.matches.map(this.renderRecipe)}
</tbody>
</table>
)
}
}
function mapStateToProps({recipes}) {
return { recipes }
};
export default connect(mapStateToProps)(RecipeList);