繁体   English   中英

React / Redux在组件构造函数中加载应用程序状态

[英]React/Redux Loading application state in component constructor

我正在渲染高阶组件,比如Application ,我需要在渲染之前从服务器获取一些数据。 我所做的,在Application I的构造函数中发出执行服务器调用并准备初始状态的loadApplicationState()动作。

一些简化的代码,

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);
  }
}

我在练习上尝试过,它运行正常。 但不确定这是一种正确的方法吗? 特别是为此目的使用构造函数。

我们在componentDidMount运行它,然后在Redux状态下测试$isLoading标志,呈现加载指示符或实际UI。 像这样的东西:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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