我正在这样从父母那里传递道具:
{Object.keys(this.state.recipes).map(key => {
return (
<Link
key={key}
to={{
pathname: `/view/${key}`,
state: {
recipe: this.state.recipes[key]
}
}}
>
<Recipe
key={key}
index={key}
recipe={this.state.recipes[key]}
deleteRecipe={this.deleteRecipe}
editRecipe={this.editRecipe}
/>
</Link>
);
})}
这是我的路由器的外观:
<BrowserRouter>
<div>
<Route exact path="/" component={App} />
<Route path="/view/:recipeId" component={ViewRecipe} />
</div>
</BrowserRouter>
从这个组件中,我正在尝试访问该道具
ViewRecipe.js
class ViewRecipe extends React.Component {
constructor(props) {
super(props);
this.state = { recipe: {} }
}
componentDidMount() {
const { recipe } = this.props.location.state;
this.setState({ recipe: recipe });
}
render() {
return (
<div>
<h1>{this.state.recipe.recipeName}</h1>
<img src={this.state.recipe.dishImg} alt="Dish" />
<ul>
{this.state.recipe.ingredients.map( ingredient => <li>{ingredient}</li>)}
</ul>
<ul>
<li>direction</li>
<li>direction</li>
<li>direction</li>
<li>direction</li>
<li>directio</li>
</ul>
</div>
);
}
}
答案 0 :(得分:2)
这可能是未定义的
<ul>
{this.state.recipe.ingredients.map( ingredient => <li>{ingredient}</li>)}
</ul>
为此,您必须修改类似的代码才能起作用
<ul>
{this.state.recipe && this.state.recipe.ingredients && this.state.recipe.ingredients.map( ingredient => <li>{ingredient}</li>)}
</ul>
在检查地图之前,我们已经检查了所有对象是否已定义
编辑:
您不能对非数组使用.map函数。 null.map结果变为undefined:)