简体   繁体   中英

React/Redux Loading application state in component constructor

I'm rendering high-order component, say Application and I need to fetch some data from server, before it's rendered. What I do, in constructor of Application I issue loadApplicationState() action, that performs server call and prepares initial state.

Some simplified code,

class Application extends Component {
  constructor(props) {
    super(props);
    const { dispatch } = this.props;

    dispatch(loadApplicationState());
  }

  render() {
    const { stateLoaded } = this.props.state;

    render (
      <div>
        { stateLoaded ? renderApp() : renderProgress() }
      </div>
    )
  }
}

function loadApplicationState() {
  return (dispatch) => {
    // fetch data and once ready,
    applicationStateLoaded(data);
  }
}

I've tried that on practice, it works fine. But not sure is this a right approach? Especially using a constructor for such purposes.

We run this in componentDidMount , and then test for an $isLoading flag in our Redux state, rendering either a loading indicator or the actual UI. Something like so:

import React, { Component } from 'react';

const mapStateToProps = (state) => ({
  $isLoading: state.initialState.$isLoading
})
const mapDispatchToProps = (dispatch) => ({
  loadApplicationState(){ dispatch(loadApplicationState()); }
})

export class Application extends Component {
  componentDidMount(){
    this.props.loadApplicationState();
  }

  render(){
    const {
      $isLoading
    } = this.props;

    {$isLoading ? (<Loader />) : <ActualApplication />}
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Application)

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