React不能在功能组件中设置undefined的属性



我正在学习react.js和它的功能组件,我有一个触发功能组件的可点击项目的问题:在任何点击之前,当页面加载时,我有一个错误Uncaught

TypeError: Cannot read properties of undefined (reading 'comments'). 

错误是当我调用{props.dish.comments}在<RenderComments…>

我的功能Dishdetail组件代码是(我删除RenderDish这不会造成错误):

function RenderComments({ comments }) {
if (comments != null) {
const rendercomments = comments.map((comment) => {
return (
<p key={comment.id} className="text-start">
{comment.comment}
<br />
<br />
-- {comment.author},{" "}
{new Intl.DateTimeFormat("en-US", {
year: "numeric",
month: "short",
day: "2-digit",
}).format(new Date(Date.parse(comment.date)))}
<br />
<br />
</p>
);
});
return (
<div className="container">
<h4 className="text-start">Comments</h4>
{rendercomments}
</div>
);
} else {
console.log("renderComments comments is null");
return <div></div>;
}
}
const Dishdetail = (props) => {
return (
<div className="row">
<div className="col-12 col-md-5 m-1">
<RenderDish dish={props.dish} />
</div>
<div className="col-12 col-md-5 m-1">
<RenderComments comments={props.dish.comments} />
</div>
</div>
);
};
export default Dishdetail;

调用者组件是这样的:

import React, { Component } from 'react';
import Menu from './MenuComponent';
import {DISHES} from '../shared/dishes'
import Dishdetail from './DishdetailComponent';
import Header from './HeaderComponent'
class Main extends Component {
constructor(props){
super(props);
this.state={dishes:DISHES,
selectedDish:null,
};
}
onDishSelect(dishId){
this.setState({selectedDish:dishId});
console.log(this.state.selectedDish)
}
render(){
return (
<div className="App">
<Header/>
<Menu dishes={this.state.dishes} onClick={(dishId)=> this.onDishSelect(dishId)}/>
<Dishdetail dish={this.state.dishes.filter((dish)=>dish.id===this.state.selectedDish)[0]} />
</div>
);
}
}
export default Main;

the dishes.js是这样的:

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"
},

EDIT: my Menu code:

import React from 'react';
import { Card, CardImg,CardImgOverlay,CardText,CardBody,CardTitle } from 'reactstrap';
function RenderMenuItem({dish,onClick}){
return(
<Card onClick={()=>onClick(dish.id)}>
<CardImg width='100' src={dish.image} alt={dish.name} />
<CardImgOverlay>
<CardTitle>{dish.name}</CardTitle>
</CardImgOverlay>
</Card>
);
}
const Menu = (props) => {
const menu = props.dishes.map((dish) => {
return (
<div key={dish.id} className="col-12 col-md-5 m-1">
<RenderMenuItem dish={dish} onClick={props.onClick}/>
</div>
);
});
return (
<div className="container">
<div className="row">
{menu}
</div>
</div>
);
}


export default Menu;

我试图做一个try类型的注释未定义/catch手动设置{props.dish.comments}为null,但我得到一个错误,我不能设置一个唯一可读的属性。

我不知道在哪里放一个if/else在盘子或评论,以适应代码和什么是盘子和评论的变量状态,当我不点击…显然是没有意义的吗?

如果你能帮我解决这个问题,而不使用类组件,那就太好了。(我也是javascript的初学者)

您可以使用useStateMain重写为功能组件。

⚠️Donot复制dishes到本地状态⚠️

import { useState } from "react"
function Main({ dishes = [], initSelection = null }) {
const [selection, setSelection] = useState(initSelection)
const selectDish = dishId => event => { setSelection(dishId) }
return <div className="App">
<Header />
<Menu dishes={dishes} onClick={selectDish} />
{ selection == null
? null
: <Dishdetail dish={dishes.find(d => d.id == selection)} />
}
</div>
}

注意Menu如何使用onClick-

function Menu({ dishes = [], onClick }) {
return <div className="Menu">
{dishes.map((dish, key) =>
<a key={key} onClick={onClick(dish.id)}>{dish.name}</a>
)}
</div>
}

最新更新