Reputation: 332
I'm a total rookie when it comes to React and this is most likely a simple issue, but it nearly drove me nuts.
The code is following:
import React, { Component } from 'react';
class Tile extends Component {
constructor(props) {
super(props);
this.state = {
priceLog: [],
diff: 'equal'
};
}
componentWillReceiveProps() {
let log = this.state.priceLog;
log = log.push(this.props.price);
this.setState({ priceLog: log });
console.log(this.state.priceLog);
}
render() {
return (
<div className="Tile">
Company: {this.props.name}<br/>
Price: {this.props.price}
<div className={this.state.diff}></div>
<button id={this.props.id}>Details</button>
</div>
);
}
}
export default Tile;
I get "Unhandled Rejection (TypeError): log.push is not a function"
when the component is rendered. All properties passed to the component are strings.
Upvotes: 6
Views: 23317
Reputation: 37604
Besides the answer from @CD, you do not want to directly manipulate a state
outside the designated setState
method. In this case you could use concat
to return a new array and assign that to the state variable. Something like this
this.setState({ priceLog: this.state.pricelog.concat(this.props.price)});
And your second call to the console.log
might not deliver the desired results since setState
is an asynchronous call. If you want to access the new state variable you have to use a callback like this
this.setState({
priceLog: this.state.pricelog.concat(this.props.price)
}, () => console.log(this.state.pricelog));
Upvotes: 15