Mat*_*lis 4 javascript reactjs redux react-redux
当前,在React中,我必须使用componentDidMount生命周期方法中的函数,在该方法中,调用操作创建者将数据提取到其中。但是,组件将使用数据,具体取决于响应的速度,以确定是否存在数据。我如何才能使该组件在数据放入其中之前不会呈现?
componentDidMount() {
this.props.getTotalHours()
this.props.getTrained()
}
Run Code Online (Sandbox Code Playgroud)
渲染功能:
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>
Run Code Online (Sandbox Code Playgroud)
Action Creator将请求返回的值存储在应用程序状态中:
export function getTotalHours() {
const url = `${ROOT_URL}dashboard/hours`
const request = axios.get(url)
return {
type: FETCH_HOURS,
payload: request
}
}
Run Code Online (Sandbox Code Playgroud)
And*_*rew 10
使用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>
)
}
Run Code Online (Sandbox Code Playgroud)
编辑:如果您关心API调用的性能,则可以与并行运行它们Promise.all。
async componentDidMount() {
const hours = this.props.getTotalHours()
const trained = this.props.getTrained()
await Promise.all([hours, trained])
this.setState({loaded: true})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7863 次 |
| 最近记录: |