javascript - 如何在获取数据之前停止组件渲染?

标签 javascript reactjs redux react-redux

目前在 React 中,我必须在 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>

Action Creator 将请求返回的值存储在应用程序状态中:

 export function getTotalHours() {
   const url = `${ROOT_URL}dashboard/hours`
   const request = axios.get(url)
   return {
     type: FETCH_HOURS,
     payload: request
   }
 }

最佳答案

使用 thenawait 控制异步操作​​,并使用 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 并行运行它们。

async componentDidMount() {
   const hours = this.props.getTotalHours()
   const trained = this.props.getTrained()
   await Promise.all([hours, trained])
   this.setState({loaded: true})
 }

关于javascript - 如何在获取数据之前停止组件渲染?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46825735/

相关文章:

javascript - React-Router:链接更新 URL 但 View 不变

javascript - React-Redux Reducers 中 Spread 语法的用途

javascript - 如何获取元素作为数组?

javascript - React 树 - 如何删除当前节点?

javascript - 更新状态时循环 react

javascript - 如何在 React-Redux 和 Typescript 中正确使用 'connect'

javascript - React - 在表格中呈现数据

javascript - grunt-init 条件标记

javascript - 轮播内幻灯片的延迟加载内容(内容是 oEmbeds/iframes)

javascript - 通过 JavaScript 设置文件输入的值会触发看似无关的事件