我正在渲染高阶组件,比如说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);
}
}
我在实践中尝试过,效果很好。但是不确定这是正确的方法吗?特别是将构造函数用于此类目的。
我们在中运行此代码componentDidMount
,然后$isLoading
在Redux状态下测试标志,以呈现加载指示器或实际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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句