【发布时间】:2017-10-19 08:33:42
【问题描述】:
目前在响应中,我必须调用 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
}
}
【问题讨论】:
-
您可以只返回一个空的 div,它在未获取数据之前不会渲染任何内容,或者您可以添加默认值并使用初始数据渲染某些内容,例如 hours = 0,当您获取数据时,您可以更新将更新您的视图的状态。
-
将 this.props.getTotalHours() 和 this.props.getTrained() 移动到 componentWillMount 并在映射之前检查应用程序状态。
标签: javascript reactjs redux react-redux