当前,在反应中,我必须使用componentDidMount生命周期方法中的函数,在该方法中,调用操作创建者将数据提取到其中。但是,组件将使用数据,具体取决于响应的速度,以确定是否存在数据。我如何才能使该组件在数据放入其中之前不会呈现?
componentDidMount() { this.props.getTotalHours() this.props.getTrained() }
渲染功能:
render() { let hours = parseInt(_.map(this.props.hours, 'hours')); let trained = _.map(this.props.trained, 'trained'); return ( <div className="o-layout--center u-margin-top-large"> <div className="o-layout__item u-width-1/2@medium u-width-1/4@large"> <div style={{width: '80%', margin: '0 auto'}}> <PieChart data={hours} goal={100} label=' Training Hours Completed'/> </div> </div>
动作创建者在应用程序状态下存储从请求返回的值:
export function getTotalHours() { const url = `${ROOT_URL}dashboard/hours` const request = axios.get(url) return { type: FETCH_HOURS, payload: request } }
使用then或控制您的异步操作,await并使用this.state来控制是否加载您的内容。仅在之后渲染您的内容this.state.loaded === true
then
await
this.state
this.state.loaded === true
constructor(props) { super(props) this.state = { loaded: false } } async componentDidMount() { await this.props.getTotalHours() await this.props.getTrained() this.setState({loaded: true}) } content() { let hours = parseInt(_.map(this.props.hours, 'hours')); let trained = _.map(this.props.trained, 'trained'); return ( <div className="o-layout--center u-margin-top-large"> <div className="o-layout__item u-width-1/2@medium u-width-1/4@large"> <div style={{width: '80%', margin: '0 auto'}}> <PieChart data={hours} goal={100} label=' Training Hours Completed'/> </div> </div> ) } render() { return ( <div> {this.state.loaded ? this.content() : null} </div> ) }
编辑:如果您关心API调用的性能,则可以与并行运行它们Promise.all。
Promise.all
async componentDidMount() { const hours = this.props.getTotalHours() const trained = this.props.getTrained() await Promise.all([hours, trained]) this.setState({loaded: true}) }