我试图更好地了解 React 组件生命周期。我正在尝试将与 React 组件生命周期相关的消息打印到控制台。在下面显示的组件中,我使用了 3 次 console.log。但是,其中 2 个在控制台中打印了两次。我正在使用铬。这就是打印到控制台的内容。
Menu Component constructor is invoked
Menu Component constructor is invoked
Menu Componen render is invoked
Menu Componen render is invoked
Menu Component componentDidMount is invoked
除了 componentDidMount 之外,为什么要重复打印三个 console.log 消息中的两个?Whid 只打印一次 componentDidMount 的 console.log。以下是组件的整个代码:
import React, { Component } from 'react';
import { Card, CardImage, CardImgOverlay, CardText, CardBody, CardTitle, CardImg } from 'reactstrap';
class Menu extends Component {
constructor(props) {
super(props);
this.state = {
selectedDish: null
}
console.log('Menu Component constructor is invoked');
}
componentDidMount() {
console.log('Menu Component componentDidMount is invoked');
}
onDishSelect(dish) {
this.setState({ selectedDish: dish});
}
renderDish(dish) {
if (dish != null) {
return(
<Card>
<CardImg width="100%" src={dish.image} alt={dish.name} />
<CardBody>
<CardTitle>{dish.name}</CardTitle>
<CardText>{dish.description}</CardText>
</CardBody>
</Card>
);
} else {
return(
<div></div>
);
}
}
render() {
const menu = this.props.dishes.map((dish) => {
return (
<div key={dish.id} className="col-12 col-md-5 m-1">
<Card onClick={() => this.onDishSelect(dish)}>
<CardImg width="100%" src={dish.image} alt={dish.name} />
<CardImgOverlay>
<CardTitle>{dish.name}</CardTitle>
</CardImgOverlay>
</Card>
</div>
);
});
console.log('Menu Componen render is invoked');
return (
<div className="container">
<div className="row">
{menu}
</div>
<div className="row">
{this.renderDish(this.state.selectedDish)}
</div>
</div>
);
}
}
export default Menu;