我遇到了一个问题,让数据流到我的道具,当组件渲染时,道具不显示。
这是包含我的RecipeList组件的容器*——注意:我从api异步获取数据btw *
import { postRecipes } from '../actions/postRecipes.js'
import { getRecipes } from '../actions/getRecipes'
class RecipesContainer extends Component{
constructor(props){
super(props)
}
componentDidMount(){
this.props.getRecipes()
}
render(){
return (
<div>
<RecipeInput postRecipes={this.props.postRecipes} />
<RecipeList recipes={this.props.recipes} />
</div>
)
}
}
const mapStateToProps = state =>{
return{
recipes: state.recipes
}
}
const mapDispatchToProps = dispatch =>{
return{
postRecipes: (recipe) => dispatch(postRecipes(recipe)),
getRecipes: () => dispatch(getRecipes())
// deleteRecipe: id => dispatch({type: 'Delete_Recipe', id})
}
}
export default connect(mapStateToProps,mapDispatchToProps)(RecipesContainer)
这是我的RecipeList组件
import React, {Component} from 'react';
import Recipe from './Recipe.js'
class RecipeList extends Component {
render() {
const { recipes } = this.props
return (
<div>
{recipes.map((recipe,index) => <Recipe recipe={recipe} key={index} />)}
</div>
)
}
}
export default RecipeList;
这里是输入并提交菜谱时映射的Recipe组件
import React, {Component} from 'react'
class Recipe extends Component {
render(){
return(
<div>
<h3>Name: {this.props.name}</h3>
<p>Category:{this.props.category}</p> <-------this one I will have to call differently since this is a one to many relationship
<p>Chef Name: {this.props.chef_name}</p>
<p>Origin: {this.props.origin}</p>
<p>Ingredients: {this.props.ingredients}</p>
</div>
)
}
}
export default Recipe
编辑:根据请求添加了getRecipe操作。
export const getRecipes = () => {
const BASE_URL = `http://localhost:10524`
const RECIPES_URL =`${BASE_URL}/recipes`
return (dispatch) => {
dispatch({ type: 'START_FETCHING_RECIPES_REQUEST' });
fetch(RECIPES_URL)
.then(response =>{ return response.json()})
.then(recipes => { return console.log(recipes), dispatch({ type: 'Get_Recipes', recipes })});
};
}
为什么它不显示我的结果?我做控制台,使我是返回我的api数据,和配方组件渲染只是html标签渲染只是很好。
您将一个名为recipe
的道具传递给您的<Recipe />
组件,但您的组件从不存在的this.props.name
读取,等等
在你的食谱列表组件中,试试这个。
{recipes ? recipes.map((recipe,index) => <Recipe recipe={recipe} key={index} />) : null}