gpt4 book ai didi

node.js - react /Redux : Need help render API Response

转载 作者:太空宇宙 更新时间:2023-11-03 22:23:56 25 4
gpt4 key购买 nike

我正在开发一个食谱应用程序。我正在使用 Yummly API,我收到了响应,但是我很困惑如何呈现从 API 返回的数据,因为响应是一个带有食谱数组的对象。当我尝试渲染数组时出现此错误:

Uncaught (in promise) Error: Objects are not valid as a React child (found: object with keys {imageUrlsBySize, sourceDisplayName, ingredients, id, smallImageUrls, recipeName, totalTimeInSeconds, attributes, flavors, rating}). If you meant to render a collection of children, use an array instead.

链接到 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);

enter image description here

最佳答案

您需要使用一些 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);

关于node.js - react /Redux : Need help render API Response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49521950/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com