Reputation: 5660
Here is my code, the class counters is calling class counter. I am trying to follow the youtube tutorials: Tutotial 1:24:00.
Here is my code:
import React, { Component } from 'react';
import Counter from './counter';
class Counters extends Component {
state = {
counters: [
{ id: 1, value: 4},
{ id: 2, value: 0},
{ id: 3, value: 0},
{ id: 4, value: 0}
]
};
render() {
return (
<div>
{ this.state.counters.map(counter =>
<Counter key={counter.id} value={counter.value} selected={true}/>)}
</div>
);
}
}
export default Counters;
and
import React, { Component } from 'react';
class Counter extends Component {
state = {
count: this.props.value,
tags: ['tag1', 'tag2', 'tag3']
};
constructor() {
super();
}
handleIncrement = product => {
console.log(product);
this.setState({ count : this.state.count + 1})
}
handleDecrement = () => {
this.setState({ count : this.state.count - 1})
}
render() {
console.log('props', this.props);
return (
<div>
<span className={this.getBadgeClasses()}>{this.formatCount()}</span>
<button onClick={() => this.handleIncrement({id:1})} className="btn btn-secondary btn-sm m-2">Increment</button>
<button onClick={this.handleDecrement} className="btn btn-secondary btn-sm m-2">Decrement</button>
</div>
);
}
getBadgeClasses() {
let classes = "badge m-2 badge-";
classes += this.state.count === 0 ? "warning" : "primary";
return classes;
}
formatCount() {
const { count } = this.state;
return count === 0 ? <h1>Zero</h1> : count;
}
}
export default Counter;
Upvotes: 0
Views: 1141
Reputation: 80986
You need to do one of the following two things to fix this:
Counter
props
argument to your constructor and pass it to superFor the second option, your constructor would look like this:
constructor(props) {
super(props);
}
But removing the constructor has the same effect.
Upvotes: 2
Reputation: 1639
This happens because where you try to initialize your state, it actually hasn't mapped the props.
This can easily be avoided by initializing your state in the constructor.
constructor(props) {
super(props);
this.state = {
count: props.value,
tags: ['tag1', 'tag2', 'tag3']
};
}
Upvotes: 1