В консоль логе "Car render" вызывается 2 раза, и основной компонент App тоже 2 раза выводит свой console.log('App render"). Почему так происходит?
import React, {Component} from 'react'
import classes from './Car.scss'
class Car extends Component {
render() {
console.log('Car render')
const inputClasses = []
if (this.props.name !== '') {
inputClasses.push(classes.green)
} else {
inputClasses.push(classes.red)
}
if (this.props.name.length > 4) {
inputClasses.push(classes.bold)
}
return(
<div className={classes.container} >
<h3>Сar name: {this.props.name}</h3>
<p>Year: <strong>{this.props.year}</strong></p>
<input
type="text"
onChange={this.props.onChangeName}
value={this.props.name}
className={inputClasses.join(' ')}
/>
<button onClick={this.props.onDelete}>Delete</button>
</div>
)
}
}
export default Car
Код родителя:
import React, {Component} from 'react';
import styles from './App.scss';
import Car from './Car/Car';
class App extends Component {
constructor(props) {
super(props)
this.state = {
cars: [
{name:'Ford',year: 2020},
// {name:'Porshe',year:2017},
// {name:'Ferrri',year:2019},
],
pageTitle: 'React Cars',
showCars: false
}
}
toggleCarsHandler = () => {
this.setState({
showCars: !this.state.showCars
})
}
onChangeName(name, index) {
const car = this.state.cars[index]
car.name = name
const cars = [...this.state.cars]
cars[index] = car
this.setState({cars})
}
deleteHandler(index) {
const cars = this.state.cars.concat()
cars.splice(index, 1)
this.setState({cars})
}
componentWillMount() {
console.log('App componentWillMount')
}
componentDidMount() {
console.log('App componentDidMount')
}
render(){
console.log('App render')
const title = this.state.pageTitle
return (
<main className={styles.main}>
<h1>{title}</h1>
<button
onClick={this.toggleCarsHandler}
className={styles['toggle-button']}
>Toggle cars</button>
<div style={{
margin: 'auto',
padding: 20
}}>
{ this.state.showCars
? this.state.cars.map((car,index)=>
<Car
key={index}
name={car.name}
year={car.year}
onDelete = {() => this.deleteHandler(index)}
onChangeName={e => this.onChangeName(e.target.value, index)}
/>)
: null
}
</div>
</main>
);
}
}
export default App;