【问题标题】:React/Redux Loading application state in component constructorReact/Redux 在组件构造函数中加载应用程序状态
【发布时间】:2015-11-30 11:02:26
【问题描述】:

我正在渲染高阶组件,比如Application,我需要在渲染之前从服务器获取一些数据。我所做的,在Application 的构造函数中发出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);
  }
}

我已经在实践中尝试过,效果很好。但不确定这是一种正确的方法吗?尤其是为了这样的目的使用构造函数。

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

    我们在 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)
    

    【讨论】:

    • componentDidMountconstructor 对于 ES6 react 应用程序不一样吗?
    • constructor componentWillMount 的替代品,而不是 componentDidMount
    • 但在我看来,构造函数是发出loadState 动作的好地方。为什么它应该只在componentDidMount 中完成?
    • constructor 不能替代 componentWillMountcomponentDidMountconstructor 的调用完全取决于 React 的心血来潮,即使组件永远不会被挂载,它也可以被调用。另一方面,componentWillMountcomponentDidMount 具有明确定义的语义。此外,最好不要在构造函数中放置副作用(如服务器调用!)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多