简体   繁体   中英

Order of component life cycle with react-redux connect and redux data

We all know that constructor -> componentWillMount -> componentDidMount is order of execution.

Now when redux comes into play and trying to access redux properties in our component life cycle. What is the order in which connect will execute so that data is available lifecycle methods ignoring and data updation to redux. The possibilities are

1. Connect (DATA AVAILABLE) -> constructor & componentWillMount & componentDidMount

2. constructor -> Connect (DATA AVAILABLE) -> componentWillMount & componentDidMount

3. constructor -> componentWillMount -> Connect (DATA AVAILABLE) -> componentDidMount

4. constructor -> componentWillMount -> componentDidMount -> Connect (DATA AVAILABLE) 

and is the order consistent or depends on the data that is loaded?

and is it different between react and react native

and is it okay to defined redux properties as required in PropType

connect is an HOC which wraps your component, so the component lifecycle method comes after the connect lifecycle. For simple understanding, you can think of connect being written like this

const connect = (mapStateToProps, mapDispatchToProps) => (Component) => {
    return class ReduxApp extends React.Component {
        // lifecycle of connect
        render() {
            return (
                 <Component {...mapStateToProps(state)} />
            )
        }
    }
}

Now whenever your state updates, connect will shallow compare the list of props to be returned to Component and if there is a change update the props, after which the component lifecycle method runs like a prop is being updated.

In short the execution initially is

Connect (DATA AVAILABLE) -> constructor & componentWillMount & componentDidMount

Once the data is updated

Connect (DATA AVAILABLE) -> componentWillReceiveProps/getDerivedStateFromProps -> componentWillUpdate -> render -> componentDidUpdate

The initial execution order would be -

Connect (DATA AVAILABLE) -> constructor & componentWillMount & Render & componentDidMount

When the site is fired up, redux connect would be initialized first with its default states and actions before the component mount life cycles. However, if there are API calls in redux, the component mount life cycles will not wait for the data. Instead component update life cycles will be invoked, if the component is already mounted and redux returns a data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM