patternjavascriptreactCritical
Can I update a component's props in React.js?
Viewed 0 times
propsupdatereactcancomponent
Problem
After starting to work with React.js, it seems like
This seems to imply that the properties CAN change on a component based upon the comparison of
props are intended to be static (passed in from the parent component), while state changes based upon events. However, I noticed in the docs a reference to componentWillReceiveProps, which specifically includes this example:componentWillReceiveProps: function(nextProps) {
this.setState({
likesIncreasing: nextProps.likeCount > this.props.likeCount
});
}This seems to imply that the properties CAN change on a component based upon the comparison of
nextProps to this.props. What am I missing? How do props change, or am I mistaken about where this gets called?Solution
A component cannot update its own props unless they are arrays or objects (having a component update its own props even if possible is an anti-pattern), but can update its state and the props of its children.
For instance, a Dashboard has a
Just before this happens, Gauge's
For instance, a Dashboard has a
speed field in its state, and passes it to a Gauge child thats displays this speed. Its render method is just return . When the Dashboard calls this.setState({speed: this.state.speed + 1}), the Gauge is re-rendered with the new value for speed.Just before this happens, Gauge's
componentWillReceiveProps is called, so that the Gauge has a chance to compare the new value to the old one.Context
Stack Overflow Q#24939623, score: 318
Revisions (0)
No revisions yet.