When we are developing our app, there are some features we always need to add, e.g. ListView components only refresh when the data in listItem is changed, initializing data before render function but not in the constructor function…
React Native component has already been implemented with many native optimization for us, but those features above are not. To do that, we need to override lifecycle function in React Native component.
First of all, this is the official site docs about the API we could use:https://facebook.github.io/react/docs/react-component.html#the-component-lifecycle
The order of lifecycle should be: constructor() -> componentWillMount() -> render() -> componentDidMount() -> [ runtime loop ] -> componentWillUnmount()
The runtime loop has two possible situations: [ new props coming update ] -> componentWillReceiveProps() -> shouldComponentUpdate() -> componentWillUpdate() -> render() -> componentDidUpdate() -> [ runtime loop ]
[ new state coming update ] -> shouldComponentUpdate() -> componentWillUpdate() -> render() -> componentDidUpdate() -> [ runtime loop ]
So the new props data will trigger the componentWillReceiveProps() function but new state data will not.
For example,in our app we could use shouldComponentUpdate(nextProps, nextState) function to decide Listview component should re-render listItem or not.
shouldComponentUpdate(nextProps, nextState) {
let changed;
const detailsChanged = nextProps.details !== this.props.details;
const dataChanged = nextProps.data !== this.props.data;
changed = detailsChanged + dataChanged;
return changed > 0;
}
Yes, but only a few. You can use setState() in componentWill(Did)Mount() and componentWillReceiveProps() functions. Never do it in other runtime loop function, it will cause endless looping.