[英]React/Redux: Need help render API Response
我正在開發食譜應用程序。 我正在使用Yummly API,但正在收到響應,但是由於如何響應是一個包含一系列食譜的對象,我對如何呈現從API返回的數據感到困惑。 當我嘗試渲染數組時,出現此錯誤:
未捕獲(承諾中)錯誤:對象作為React子對象無效(找到:帶有鍵{imageUrlsBySize,sourceDisplayName,Ingredients,id,smallImageUrls,recipeName,totalTimeInSeconds,attribute,flavors,rating}的對象)。 如果要渲染子級集合,請改用數組。
鏈接到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);
您需要在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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.