本文介绍了反应:如何在使用"this.state.x"之前等待数据?变成一个功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习React,对于初学者来说有些东西不那么容易...

I'm currently learning React, and some stuff are not so easy for a newbie...

我有一个简单的组件,该组件renders这样(请注意,由于函数getSlots ,它呈现了li数组):

I have a simple component which renders this (note that it renders a li array thanks to function getSlots):

render () {
    return (
        <ul>
          {this.getSlots(this.state.viewing).map(item => <li key={item}>{item}</li>)}
        </ul>
    )
  }

功能getSlots是:

constructor (props) {...}

getSlots (viewing) {

    SOME STUFF...

    const monday = this.state.house.monday

    return SOME STUFF...
  }

componentDidMount () {...}

render () {...}

重点是getSlots需要在componendDidMount中读取的数据才能正常工作.实际上,此时getSlots不起作用(崩溃),因为它在获取数据之前就已运行(this.state.house.monday在运行时为空").

The point is that getSlots needs data to be fetched in componendDidMount to work. Indeed, at this time, getSlots doesn't work (it crashes) because it runs before data are fetched (this.state.house.monday is "empty" when it runs).

如何在运行getSlots之前等待数据被提取?谢谢您的提示.

How do I wait for data to be fetched before running getSlots? Thanks for your clue.

推荐答案

您将需要有条件地进行渲染.提供要在异步所需数据之前加载的加载状态.您将需要以下内容:

You're going to need to conditionally render. Provide a loading state to be loaded prior to asynchronously required data. You'll want something like the following:

class WrapperComponent extends PureComponent {
    constructor(props) {
        super(props);

        this.state = {
            isLoaded: false,
            data: null
        };
    }

    componentDidMount() {
        MyApiCall.then(
            res => this.setState({
                // using spread operator, you will need transform-object-rest-spread from babel or
                // another transpiler to use this
                ...this.state, // spreading in state for future proofing
                isLoaded: true,
                data: res.data
            })
        );
    }

    render() {
        const { isLoaded, data } = this.state;
        return (
            {
                isLoaded ?
                    <PresentaionComponentThatRequiresAsyncData data={ data } /> :
                    <LoadingSpinner /> // or whatever loading state you want, could be null
            }
        );
    }
}

这篇关于反应:如何在使用"this.state.x"之前等待数据?变成一个功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 22:47