I\'m studying change detection mechanism and I\'m having some troubles with reactjs case.
When props are changed in a react component, this component is \"rerendered\" (
Try to imagine there are 2 things here:
You need to call this.setState(), this would update the state inside the current component, and subsequently trigger an update (automatically call render()) of this component
This would trigger the props/newProps of this COMPONENT to be updated, and subsequently your component is updated by calling this.setState() inside the component (componentWillReceiveProps is a lifecycle method from React)
class MyComponent extends React.Component {
// initially how the state is set to MyComponent
constructor(props) {
super(props);
this.state = {name: this.props.name};
}
// own method to be called inside MyComponent
updateName(e) {
const newName = e.target.value;
if (this.state.name !== newName) {
this.setState({name:newName});
}
}
// changes from the outside
componentWillReceiveProps(nextProps) {
const newName = nextProps.name;
if (this.state.name !== newName) {
this.setState({name:newName});
}
}
render() {
return(
{this.state.name}
)
}
}
It's worth pointing out that this.setState() would automatically trigger render(), while this.state.name = 'Bob' wouldn't trigger render().