【发布时间】:2020-06-24 03:56:13
【问题描述】:
我将道具从一个组件传递到位于另一个文件中的另一个组件。我已经在两个组件中正确地创建了构造函数,但是我仍然遇到这个错误,作为一个新手,我无法解决这个问题。我在谷歌和 StackOverflow 上搜索过,但没有得到任何满意的结果。 App.js 文件:-
import React, {Component} from 'react';
import Menu from './component/MenuComponent';
import {DISHES} from './shared/dishes';
import logo from './logo.svg';
import {Navbar,NavbarBrand, Container} from 'reactstrap';
import { render } from 'react-dom';
//eslint-disable-next-line
class App extends Component{
constructor(props){
super(props);
this.state={
dishes:DISHES
}
}
render() {
return(
<div className='App'>
<Navbar dark color ="primary">
<div className="Container">
<NavbarBrand href="#">Saurav Pandey</NavbarBrand>
</div>
</Navbar>
<Menu dishes={this.state.dishes} />
</div>
);
}
}
export default App;
import React, { Component } from 'react';
import { Card, CardBody, CardText, CardTitle, CardImg, CardImgOverlay } from 'reactstrap';
class Menu extends Component {
constructor(props){
super(props);
this.state={
selectedDish:null
}
console.log('Menu component constructor is invoked');
}
onDishSelect(dish){
this.setState({selectedDish:dish});
}
renderDish(dish) {
if(dish!=null) {
return(
<Card>
<CardImg top src={dish.image} alt={dish.name} />
<CardBody>
<CardTitle>{dish.name}</CardTitle>
<CardText>{dish.description}</CardText>
</CardBody>
</Card>
);
} else {
return(
<div>not found!</div>
);
}
}
render() {
if(this.props.dishes) {
const menu=this.props.dishes.map((dish) => {
return(
<div className="col-12 col-md-5 m-1">
<Card key={dish.id} onClick={()=>this.onDishSelect(dish)}>
<CardImg width="100%" src={dish.image} alt={dish.name}/>
<CardImgOverlay>
<CardTitle>
{dish.name}
</CardTitle>
</CardImgOverlay>
</Card>
</div>
);
});
return(
<div className="container">
<div className="row">
{menu}
</div>
<div className="row">
<div className="col-10 md-2 mt-1">
{this.renderDish(this.state.selectedDish)}
</div>
</div>
</div>
);
} else {
return(
<div>
not found
</div>
);
}
};
}
export default Menu;
其他渲染文件在单独的文件中正确创建。 菜肴是一个数组,它看起来像:-
export const DISHES =
[
{
id: 0,
name:'Uthappizza',
image: 'assets/images/uthappizza.png',
category: 'mains',
label:'Hot',
price:'4.99',
description:'A unique combination of Indian Uthappam (pancake) and Italian pizza, topped with Cerignola olives, ripe vine cherry tomatoes, Vidalia onion, Guntur chillies and Buffalo Paneer.',
comments: [
{
id: 0,
rating: 5,
comment: "Imagine all the eatables, living in conFusion!",
author: "John Lemon",
date: "2012-10-16T17:57:28.556094Z"
},
{
id: 1,
rating: 4,
comment: "Sends anyone to heaven, I wish I could get my mother-in-law to eat it!",
author: "Paul McVites",
date: "2014-09-05T17:57:28.556094Z"
}
]
【问题讨论】:
-
dishes的实际外观如何?是数组吗 -
if(!this.props.dishes)在这里你想要map而不是dishes如果它不存在。 -
你的菜是什么样子的,如果你能在问题中添加
'./shared/dishes';会更有帮助 -
我也更新了菜谱文件。我尝试了 if 和 else 语句,因为只是为了检查其余代码是否正确。
-
@BeHappy 我也更新了这部分。我认为我收到了这个错误,因为这里 props 的值为 NULL。我不明白为什么会发生这个问题,而不是创建正确的构造函数。
标签: javascript reactjs react-props