反应:如何在将“ this.state.x”用于函数之前等待数据?

ner*_*lip 3 javascript asynchronous reactjs

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

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

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

功能getSlots是:

constructor (props) {...}

getSlots (viewing) {

    SOME STUFF...

    const monday = this.state.house.monday

    return SOME STUFF...
  }

componentDidMount () {...}

render () {...}
Run Code Online (Sandbox Code Playgroud)

关键是getSlots需要获取数据componendDidMount才能正常工作。确实,这时getSlots不起作用(崩溃),因为它在获取数据之前运行(this.state.house.monday运行时为“空”)。

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

Kyl*_*son 6

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

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
            }
        );
    }
}
Run Code Online (Sandbox Code Playgroud)