目前在 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
}
}
最佳答案
使用 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
并行运行它们。
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/