Reputation: 1147
I have this code in my Product component to assign props received to a state this state is not assigned when I create a new Product and render it on the parent by changing the state of Products list and hence re-loading products and even for existing objects, the colours and sizing don't appear unless you first load the page then refresh it.
The implementation is as follows:
1) They are defined in the state of the product class
this.state = {
colorsPicked: [],
newProductSizes: []
};
2) They are passed in the component's parent class as props as follows:
<Product
colors={product.colors}
sizes={product.sizes}
updateProducts={this.updateProducts}
/>
3) They are supposedly set in the product class as follows:
async componentWillReceiveProps(props) {
this.setState({
colorsPicked: props.colors,
newProductSizes: props.sizes
});
}
Upvotes: 0
Views: 1475
Reputation: 66
Try setting them via your constructor:
class Item extends Component {
constructor(props) {
this.state = {
colorsPicked: props.colors,
newProductSizes: props.sizes
}
}
}
Upvotes: 4
Reputation: 31335
I think your best answer should be in here:
React: You probably don't need derived state
If you absolutely must, you can try something with:
static getDerivedStateFromProps() This method will run before every render, including the first one.
Upvotes: 4